题目

power-of-two


算法

* 直接模拟

* 技巧


代码

* 直接模拟


class Solution {

public:

    bool isPowerOfTwo(int n) {

        int cnt = 0;

        while (n > 0) {

            cnt += (n & 1);

            n >>= 1;

        }

        return cnt == 1;

    } 

};

* 技巧


class Solution {

public:

    bool isPowerOfTwo(int n) {

        return (n > 0) && (!(n & (n - 1)));

    } 

};

results matching ""

    No results matching ""