Power of Two
Given an integer, write a function to determine if it is a power of two.
判断给出的数,是否为2的次方,如1,2,4,8,16...
class Solution {
public:
bool isPowerOfTwo(int n) {
if (!n) return false; //等于0的情况
while (n != 1){ // 二进制第一个数肯定是1,不判断
if (n&1) return false; // 为1 则不是2的次方
n = n >> 1;
}
return true;
}
};class Solution {
public:
bool isPowerOfTwo(int n) {
//if (!n) return false; // 有可能是负数,故不行
if (n <= 0) return false;
return ( n&(n - 1) )== 0;
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/u014705854/article/details/46931333