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
相關用法
- Java Guava IntMath gcd(int a, int b)用法及代碼示例
- Java Guava IntMath pow(int b, int k)用法及代碼示例
- Java Guava IntMath mean()用法及代碼示例
- Java Guava IntMath mod()用法及代碼示例
- Java Guava IntMath ceilingPowerOfTwo()用法及代碼示例
- Java Guava IntMath binomial()用法及代碼示例
- Java Guava IntMath floorPowerOfTwo()用法及代碼示例
- Java Guava IntMath isPrime()用法及代碼示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代碼示例
- Java Guava LongMath isPowerOfTwo(long x)用法及代碼示例
- Java IntMath.checkedAdd(int a, int b)用法及代碼示例
- Java IntMath.checkedMultiply(int a, int b)用法及代碼示例
- Java IntMath.checkedPow(int b, int k)用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 Java Guava | isPowerOfTwo() method IntMath Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。