您的位置:首页 > 其它

lintcode-easy-O(1) Check Power of 2

2016-03-03 07:49 260 查看
Using O(1) time to check whether an integer n is a power of
2
.

For
n=4
, return
true
;

For
n=5
, return
false
;

这道题就是看一下这个int二进制各位上总共是否只有一个1,如果只有一个1则是2的n次方。但是要注意特殊情况,如果这个数是Integer.MIN_VALUE,也只有一位是1,但是这个数是负数,所以不是2的n次方。

class Solution {
/*
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
// write your code here
int count = 0;

if(n == Integer.MIN_VALUE)
return false;

for(int i = 0; i < 32; i++){
if(((n >> i) & 1) == 1)
count++;
}

return count == 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: