Leetcode 231. Power of Two
题目描述:检验一个数是否为2的整数幂
题目链接:Leetcode 231. Power of Two
基本思路:查看位数为1的是否只有一个,是的话就是,否的话就不是。(考虑正负,左移是补0补1取决于位数)
位操作技巧,就是n&(n-1)结果为n取出最右侧1后的数。
代码如下
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
ans = 0
while(n):
ans += (n&1)
n >>= 1
return True if ans==1 else False
网友答案:
Power of 2 means only one bit of n is ‘1’, so use the trick n&(n-1)==0 to judge whether that is the case
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
return !(n&(n-1));
}
};