Given an integer, write a function to determine if it is a power of two.
原题链接
思路:如果那个数是2的幂,那么二进制表示中一定只有一个1。
例如
- 1:0001
- 2:0010
- 4:0100
- …
所以就想按位来检验是否为2的幂
class Solution {
public:
bool isPowerOfTwo(int n) {
bool ans = false;
int temp = n;
while(temp!=0)
{
if(temp&0x01)
{
if(!ans) ans = true;
else
{
ans = false;
break;
}
}
temp = temp >> 1;
}
return ans;
}
};
还有一种方法是判断是一直对2取余,看是否为零,如果一直为0那么就为true,但是我感觉这两种应该差不多。