首先除法的要注意corner case 0,1之类的
然后就是另一个方法是数bit 1 的个数 2的power只能有一个1
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
}return ((n & (n-1))==0 && n>0);
本文介绍了如何通过位运算的方法来判断一个整数是否为2的幂次方,并详细解释了背后的原理。这种方法适用于各种编程语言,特别是针对整数操作的高效算法。
首先除法的要注意corner case 0,1之类的
然后就是另一个方法是数bit 1 的个数 2的power只能有一个1
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
}return ((n & (n-1))==0 && n>0);
232

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