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


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