Power of Two(算法)

Power of Two(算法)

4: 2 2 2^2 true
9: 3 2 3^2 false
16: 4 2 4^2 = 2 4 2^4 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));
}
发布了191 篇原创文章 · 获赞 23 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/pureszgd/article/details/102851165
今日推荐