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


Java Guava BigIntegerMath floorPowerOfTwo()用法及代碼示例


Guava BigIntegerMath類的floorPowerOfTwo(BigInteger x)方法返回小於或等於x的2的最大冪。這等效於BigInteger.valueOf(2).pow(log2(x,FLOOR))。

用法:

public static BigInteger floorPowerOfTwo(BigInteger x)

參數:此方法將BigInteger x作為其底方冪為2的參數。


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

異常:如果x <= 0,則此方法引發IllegalArgumentException。

以下示例說明了BifIntegerMath.floorPowerOfTwo()方法:

範例1:

// Java code to show implementation of 
// floorPowerOfTwo() method 
// of Guava's BigIntegerMath class 
  
import java.math.*; 
import com.google.common.math.BigIntegerMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        BigInteger n1 = BigInteger.valueOf(10); 
  
        // Using floorPowerOfTwo(BigInteger x) method 
        // of Guava's BigIntegerMath class 
        BigInteger 
            ans1 
            = BigIntegerMath.floorPowerOfTwo(n1); 
  
        System.out.println("Largest power of 2 less "
                           + "than or equal to " + n1 
                           + " is:" + ans1); 
  
        BigInteger n2 = BigInteger.valueOf(127); 
  
        // Using floorPowerOfTwo(BigInteger x) method 
        // of Guava's BigIntegerMath class 
        BigInteger 
            ans2 
            = BigIntegerMath.floorPowerOfTwo(n2); 
  
        System.out.println("Largest power of 2 less "
                           + "than or equal to " + n2 
                           + " is:" + ans2); 
    } 
}

輸出:

Largest power of 2 less than or equal to 10 is:8
Largest power of 2 less than or equal to 127 is:64

範例2:顯示IllegalArgumentException

// Java code to show implementation of 
// floorPowerOfTwo(BigInteger x) method 
// of Guava's BigIntegerMath class 
  
import java.math.*; 
import com.google.common.math.BigIntegerMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
  
        try { 
            BigInteger n1 = BigInteger.valueOf(-3); 
  
            // Using floorPowerOfTwo(BigInteger x) method 
            // of Guava's BigIntegerMath class 
            // This should raise "IllegalArgumentException" 
            // as x <= 0 
            BigInteger 
                ans1 
                = BigIntegerMath.floorPowerOfTwo(n1); 
  
            System.out.println("Largest power of 2 less "
                               + "than or equal to " + n1 
                               + " is:" + ans1); 
        } 
        catch (Exception e) { 
            System.out.println("Exception:" + e); 
        } 
    } 
}

輸出:

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

參考: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#floorPowerOfTwo-java.math.BigInteger-



相關用法


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