方法一:
利用性质:2的幂次的2进制表示中只有一个1;
class Solution {
public boolean isPowerOfTwo(int n) {
if(n == 0) return false;
while(n%2==0){
n = n >>1;
}
return n==1;
}
}
方法二:
x & (-x) 可以获取到二进制中最右边的 1,且其它位设置为 0。
x 和 -x−x 只有一个共同点:最右边的 1。这说明 x & (-x) 将保留最右边的 1。并将其他的位设置为 0。
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;//对int的INteger.MIN_VALUE 即 -2147483648 要特殊处理;这个数不是2的幂次;
return (x & (-x)) == x;
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
//对int的INteger.MIN_VALUE 即 -2147483648 要特殊处理;这个数不是2的幂次;
if(n == Integer.MIN_VALUE) return false;
int x = n;
return (x & (-x)) == x;
}
}
方法三:
x & (x - 1) 可以将最右边的 1 设置为 0。
检测是否为 2 的幂:
2 的幂二进制表示只含有一个 1。
x & (x - 1) 操作会将 2 的幂设置为 0,因此判断是否为 2 的幂是:判断 x & (x - 1) == 0。
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (x - 1)) == 0;
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
if(n == Integer.MIN_VALUE) return false;
int x = n;
return (x & (x-1)) == 0;
}
}