Power of Two ----- 判断一个数是不是2的幂

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating

all test cases.

Subscribe to see which companies asked this question


分析:

这里的题意是求解一个数n是不是2的幂。


这里我使用位运算来求解。


详解:

点击打开链接

方法一:


<pre name="code" class="html">class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n>0) && (!(n&(n-1)));
    }
};

 
  

Power of Two ----- 判断一个数是不是2的幂_第1张图片

方法二:

class Solution {
public:
   bool isPowerOfTwo(int n) {
        int count = 0;
        while (n > 0)
        {
            count+=(n&0x01);
            n>>=1;
        }
        return count==1;
    }
}
};



你可能感兴趣的:(Power of Two ----- 判断一个数是不是2的幂)