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


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


Guava IntMath類的floorPowerOfTwo()方法接受一個參數,並返回比該參數中傳遞的值小2的最大冪。這等效於:checkedPow(2,log2(x,FLOOR))。

用法:

public static int floorPowerOfTwo(int x)

參數:此方法接受單個參數x,它是整數值。


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

異常:如果x <= 0,則方法floorPowerOfTwo(int x)拋出IllegalArgumentException。

範例1:

// Java code to show implementation 
// of floorPowerOfTwo(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 n1 = 10; 
  
        // Using floorPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        int ans1 = IntMath.floorPowerOfTwo(n1); 
  
        System.out.println("Largest power of 2 less "
                           + "than or equal to " + n1 + " is:" + ans1); 
  
        int n2 = 127; 
  
        // Using floorPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        int ans2 = IntMath.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:

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

輸出:

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

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



相關用法


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