Power of Two(算法)

4: 222^222 true
9: 323^232 false
16: 424^242 = 242^424 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));
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐