leetcode 231. Power of Two

1. 

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        while(n!=1) {
            if(n%2) return false;
            n/=2;
        }
        return true;
    }
};

2. 如果是2的倍数,那么这个数的二进制中只有1个1,其余都是0;如果一个数的二进制中只有一个1,那么(n&(n-1))=0

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

 

posted @ 2020-06-27 18:13  qiujiejie  阅读(97)  评论(0编辑  收藏  举报