Given an integer, write a function to determine if it is a power of two.
[思路]
1)考虑各种边界情况。输入是整型值,说明不用考虑2的负指数情况。
2)如果一个数是二的倍数,说明他的二进制形式只有一位是1。做好判断即可。
循环判断1的位数解法最容易想到。
Leetcode上有种解法,就是让n&n-1,如果n只含有一个1那么结果就是零。
简单解法:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
int count = 0;
while(n!=0){
if(n%2!=0){
count++;
}
n = n>>1;
if(count>1)
return false;
}
return true;
}
};神奇解法:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
n &= n-1;
return n==0 ;
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/ciaoliang/article/details/46931427