题目描述:
Using O(1) time to check whether an integer n is a power of 2
.
Example
For n=4
, return true
;
For n=5
, return false
;
Challenge
题目思路:
O(1) time
每个int32都一共只有32位,而如果是2的power,那么这32位中必须只有一位是‘1’。
Mycode(AC = 39ms):
class Solution {
public:
/*
* @param n: An integer
* @return: True or false
*/
bool checkPowerOf2(int n) {
// write your code here
long long ln = (long long)n;
if (ln < 0) return false;
// traverse all the 32 bits, the result
// should only contain one '1'
int count = 0;
for (int i = 0; i < 32; i++) {
count += ln % 2;
ln >>= 1;
}
return count == 1;
}
};