Guava – IntMath.checkedPow()方法及实例

来源:这里教程网 时间:2026-02-17 21:40:49 作者:

Guava – IntMath.checkedPow()方法及示例

checkedPow(int b, int k)是Guava的一个方法。 IntMath类 它接受两个参数 b and k 并用于寻找b的k次方。

语法:

public static int checkedPow(int b, int k)

参数: 该方法接受两个参数,b和k。参数b被称为基数,它被提高到k次方。

返回值: 该方法返回b的k次方。

异常情况: 如果b的k次方在有符号int算术中溢出,方法checkedPow(int b, int k)将抛出ArithmeticException。

下面的例子说明了上述方法的实现。

例1:

// Java code to show implementation of// checkedPow(int b, int k) 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 b1 = 5;        int k1 = 7;          // Using checkedPow(int b, int k) method        // of Guava's IntMath class        int ans1 = IntMath.checkedPow(b1, k1);          System.out.println(b1 + " to the "                           + k1 + "th power is: "                           + ans1);          int b2 = 19;        int k2 = 4;          // Using checkedPow(int b, int k) method        // of Guava's IntMath class        int ans2 = IntMath.checkedPow(b2, k2);          System.out.println(b2 + " to the " + k2                           + "th power is: "                           + ans2);    }}

输出:

5 to the 7th power is: 7812519 to the 4th power is: 130321

例2:

// Java code to show implementation of// checkedPow(int b, int k) method of// Guava's IntMath class  import java.math.RoundingMode;import com.google.common.math.IntMath;  class GFG {      static int findPow(int b, int k)    {        try {              // Using checkedPow(int b, int k) method of            // Guava's IntMath class            // This should raise "ArithmeticException" as            // b to the kth power overflows in            // signed int arithmetic            int ans = IntMath.checkedPow(b, k);              // Return the answer            return ans;        }        catch (Exception e) {            System.out.println(e);            return -1;        }    }      // Driver code    public static void main(String args[])    {        int b = 20;        int k = 25;          try {              // Function calling            findPow(b, k);        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

java.lang.ArithmeticException: overflow

参考资料:

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

相关推荐