Leetcode[231] Power of Two
29 Nov 2015###Task1 Given an integer, write a function to determine if it is a power of two.
###Python
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
return (n & (n - 1)) == 0
###Java
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
int res = (n - 1) & n;
return res == 0;
}
}
###Points
如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0 等价于:n & (n - 1) = 0,且n > 0