當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Guava IntMath isPowerOfTwo()用法及代碼示例


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

參考:
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#isPowerOfTwo-int-



相關用法


注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 Java Guava | isPowerOfTwo() method IntMath Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。