📌  相关文章
📜  Java番石榴 | IntMath 类的 ceilingPowerOfTwo() 方法

📅  最后修改于: 2022-05-13 01:55:35.703000             🧑  作者: Mango

Java番石榴 | 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:如果 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-