问题:
用 O(1) 时间检测整数 n 是否是 2 的幂次。
样例:
Example 1:
Input: 4
Output: true
Example 2:
Input: 5
Output: false
python:
class Solution:
"""
@param n: An integer
@return: True or false
"""
def checkPowerOf2(self, n):
# write your code here
if n < 1:
return False
if (n&(n-1)) == 0:
return True
return False
C++:
class Solution {
public:
/**
* @param n: An integer
* @return: True or false
*/
bool checkPowerOf2(int n) {
// write your code here
if(n < 1)
{
return false;
}
if((n&(n-1)) == 0)
{
return true;
}
return false;
}
};
PS:注意==的优先级比&高