Guava IntMath类的isPowerOfTwo()方法用于检查数字是否为2的幂。它接受要检查的数字作为参数,并根据数字是否为2的幂返回布尔值true或false。
用法:
public static boolean isPowerOfTwo(int x)
参数:此方法接受单个参数x,该参数为整数类型。
返回值:如果x代表2的幂,则该方法返回true;如果x代表2的幂,则该方法返回false。
异常:该方法没有任何异常。
注意:这与Integer.bitCount(x)== 1不同,因为Integer.bitCount(Integer.MIN_VALUE)== 1,但Integer.MIN_VALUE不是2的幂。
范例1:
// Java code to show implementation of
// isPowerOfTwo(int x) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int a1 = 63;
// Using isPowerOfTwo(int x) method
// of Guava's IntMath class
if (IntMath.isPowerOfTwo(a1))
System.out.println(a1 + " is power of 2");
else
System.out.println(a1 + " is not power of 2");
int a2 = 1024;
// Using isPowerOfTwo(int x) method
// of Guava's IntMath class
if (IntMath.isPowerOfTwo(a2))
System.out.println(a2 + " is power of 2");
else
System.out.println(a2 + " is not power of 2");
}
}
输出:
63 is not power of 2
1024 is power of 2
范例2:
// Java code to show implementation of
// isPowerOfTwo(int x) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int a1 = 10;
// Using isPowerOfTwo(int x) method
// of Guava's IntMath class
if (IntMath.isPowerOfTwo(a1))
System.out.println(a1 + " is power of 2");
else
System.out.println(a1 + " is not power of 2");
int a2 = 256;
// Using isPowerOfTwo(int x) method
// of Guava's IntMath class
if (IntMath.isPowerOfTwo(a2))
System.out.println(a2 + " is power of 2");
else
System.out.println(a2 + " is not power of 2");
}
}
输出:
10 is not power of 2
256 is power of 2