Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
如果是power of two, 则2进制表达中,有且仅有一个1. 可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断 N & (N-1) 是否为0.
public boolean isPowerOfTwo(int n) {
if (n <= 0)
return false;
return (n & (n - 1)) == 0;
}

该博客介绍了一道LeetCode问题,即判断一个整数是否为2的幂。2的幂在二进制表示中只有一个1,可以通过位运算检查`N & (N-1)`是否为0来确定。
398

被折叠的 条评论
为什么被折叠?



