leetcode-231-Power of Two
时间:2015-07-17 21:06:00
收藏:0
阅读:266
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;
}
};利用 n&(n - 1) ,即将二进制的最后一个1变为0
如果是2的次方,则n&(n - 1)=0
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
评论(0)