[LeetCode] Power of Two

Given an integer, write a function to determine if it is a power of two.

判断一个数是不是2的幂。

思路,找出该数中二进制位1的个数

时间复杂度:O(n)

代码:

    public boolean isPowerOfTwo(int n) {
        if(n<1)
            return false;
        int cnt=0;
        while(n>=1)
        {
            if((n&0x0001) == 1)cnt++;
            n=n>>1;
        }
        return cnt==1;
    }

 优化:

    return   n&(n-1)==0; 

扩展:

原文地址:https://www.cnblogs.com/maydow/p/4641038.html