如何使用 JAVA 中的 a&(a-1)==0 检查 Long 数据类型数字的 2 次方或不
How can i check a Long data type number a power of 2 or not using a&(a-1)==0 in JAVA
这是我试过的。它说第二个操作数是布尔值,而第一个是长操作数。所以 & 运算符对于 long 和 boolean 是未定义的。
public static void powerOfTwo(long a){
if(a & (a-1) == 0 )
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
您必须将表达式括在额外的括号中:
public static void powerOfTwo(long a) {
if ((a & (a - 1)) == 0)
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
那是因为运算符 ==
优先于 &
(参见 here),所以没有大括号,您有
a & (a - 1) == 0
与
相同
a & ((a - 1) == 0)
然后编译器抱怨将长整数 (a
) 与布尔值 (a-1 == 0)
进行比较
您可以使用
return a != 0 && ((a & (a-1)) == 0);
然而这是模糊的。更简单的方法是
return Long.bitCount(a) == 1
这也不是很明显,但是恰好设置了一位意味着它必须是 2 的幂。
这是我试过的。它说第二个操作数是布尔值,而第一个是长操作数。所以 & 运算符对于 long 和 boolean 是未定义的。
public static void powerOfTwo(long a){
if(a & (a-1) == 0 )
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
您必须将表达式括在额外的括号中:
public static void powerOfTwo(long a) {
if ((a & (a - 1)) == 0)
System.out.println("it's a power of two");
else
System.out.println("NOT a power of two");
}
那是因为运算符 ==
优先于 &
(参见 here),所以没有大括号,您有
a & (a - 1) == 0
与
相同a & ((a - 1) == 0)
然后编译器抱怨将长整数 (a
) 与布尔值 (a-1 == 0)
您可以使用
return a != 0 && ((a & (a-1)) == 0);
然而这是模糊的。更简单的方法是
return Long.bitCount(a) == 1
这也不是很明显,但是恰好设置了一位意味着它必须是 2 的幂。