Leetcode #231. Power of Two

Leetcode #231. Power of Two

题目

https://leetcode.com/problems/power-of-two/description/

代码

我的:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        int num = 0;
        for (int i = 0; i < 32; i++) {
            num += (n & 0x1);
            n = n >> 1;
        }
        return num == 1;
    }
};

别人的:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        return (n & (n - 1)) == 0;
    }
};
点赞