Power of Two(算法)

mac2025-01-20  53

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)