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

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

Java番石榴 | floorPowerOfTwo() 方法 IntMath 类

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-