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


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


Guava的IntMath類的ceilingPowerOfTwo(int x)方法接受一個參數,並計算出比該參數中傳遞的值大2的最小冪。此方法等效於checkedPow(2,log2(x,CEILING))。

用法:

public static int ceilingPowerOfTwo(int x)

參數:此方法接受單個參數x,該參數為整數類型,並返回比參數中傳遞的值大2的最小冪。


返回值:大於或等於x的2的最小冪。

異常:

  • IllegalArgumentException:如果x <= 0,則此方法引發IllegalArgumentException。
  • ArithmeticException:如果next-higher的2的冪不能表示為int,即x> 2^30時,此方法將引發ArithmeticException。

下麵的示例說明IntMath類的ceilingPowerOfTwo()方法:

範例1:

// Java code to show implementation of  
// isPrime(int n) 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 isPrime(int n)  
        // method of Guava's IntMath class 
        if(IntMath.isPrime(a1)) 
        System.out.println(a1 + " is a prime number"); 
        else
        System.out.println(a1 + " is not a prime number"); 
           
        int a2 = 17; 
           
        // Using isPrime(int n)  
        // method of Guava's IntMath class 
        if(IntMath.isPrime(a2)) 
        System.out.println(a2 + " is a prime number"); 
        else
        System.out.println(a2 + " is not a prime number"); 
    }  
} 

輸出

Smallest power of 2 greater than or equal to 25 is:32
Smallest power of 2 greater than or equal to 65 is:128

範例2:

// Java code to show implementation of  
// ceilingPowerOfTwo(int x) method of Guava's 
// IntMath class 
import java.math.RoundingMode;  
import com.google.common.math.IntMath;  
  
class GFG {  
      
    static int findCeilPow(int x)  
    {  
        try {  
              
            // Using ceilingPowerOfTwo(int x)  
            // method of Guava's IntMath class  
            // This should throw "IllegalArgumentException"  
            // as x <= 0 
            int ans = IntMath.ceilingPowerOfTwo(x);  
    
            // Return the answer  
            return ans;  
        }  
        catch (Exception e) {  
            System.out.println(e);  
            return -1;  
        }  
    }  
  
    // Driver code  
    public static void main(String args[])  
    {  
        int n = -4; 
          
        try {  
            // Function calling 
            findCeilPow(n);;  
        }  
        catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
} 

輸出

java.lang.IllegalArgumentException:x (-4) must be > 0

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



相關用法


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