当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。