Power of Two(算法)
4:
2
2
2^2
22 true
9:
3
2
3^2
32 false
16:
4
2
4^2
42 =
2
4
2^4
24 true
1.mod;
2.log2 => int;
3.位运算;
x & (x - 1)
判断:
x != 0 && x & (x - 1) == 0
python
def isPowerOfTwo(self, n):
return n > 0 and not (n & n - 1)
java
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
所有评论(0)