Guava - IntMath 类
IntMath 提供了 int 上的实用方法。
类声明
以下是 com.google.common.math.IntMath 类的声明 −
@GwtCompatible(emulated = true) public final class IntMath extends Object
方法
Sr.No | 方法及描述 |
---|---|
1 |
static int binomial(int n, int k) 返回 n 选择 k,也称为 n 和 k 的二项式系数,如果结果不适合 int,则返回 Integer.MAX_VALUE。 |
2 |
static int checkedAdd(int a, int b) 返回a和b的和,前提是它不溢出。 |
3 |
static int checkedMultiply(int a, int b) 返回 a 和 b 的乘积,前提是它不溢出。 |
4 |
static int checkedPow(int b, int k) 返回b的k次方,前提是它不溢出。 |
5 |
static int checkedSubtract(int a, int b) 返回 a 和 b 的差值,前提是它不溢出。 |
6 |
static int divide(int p, int q, RoundingMode mode) 返回 p 除以 q 的结果,使用指定的 RoundingMode 进行舍入。 |
7 |
static int factorial(int n) 返回 n!,即前 n 个正整数的乘积,如果 n == 0,则返回 1;如果结果不适合 int,则返回 Integer.MAX_VALUE。 |
8 |
static int gcd(int a, int b) 返回a、b的最大公约数。 |
9 |
static boolean isPowerOfTwo(int x) 如果 x 代表 2 的幂,则返回 true。 |
10 |
static int log10(int x, RoundingMode mode) 返回 x 以 10 为底的对数,根据指定的舍入模式进行舍入。 |
11 |
static int log2(int x, RoundingMode mode) 返回 x 以 2 为底的对数,根据指定的舍入模式进行舍入。 |
12 |
static int mean(int x, int y) 返回 x 和 y 的算术平均值,向负无穷大舍入。 |
13 |
static int mod(int x, int m) 返回 x mod m,小于 m 的非负值。 |
14 |
static int pow(int b, int k) 返回b的k次方。 |
15 |
static int sqrt(int x, RoundingMode mode) 返回 x 的平方根,并使用指定的舍入模式进行舍入。 |
继承的方法
该类继承了以下类的方法 −
- java.lang.Object
Example of IntMath Class
使用您在 C:/> Guava 中选择的任何编辑器创建以下 java 程序。
GuavaTester.java
import java.math.RoundingMode; import com.google.common.math.IntMath; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testIntMath(); } private void testIntMath() { try { System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY)); try { //exception will be thrown as 100 is not completely divisible by 3 // thus rounding is required, and RoundingMode is set as UNNESSARY System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Log2(2): " + IntMath.log2(2, RoundingMode.HALF_EVEN)); System.out.println("Log10(10): " + IntMath.log10(10, RoundingMode.HALF_EVEN)); System.out.println("sqrt(100): " + IntMath.sqrt(IntMath.pow(10,2), RoundingMode.HALF_EVEN)); System.out.println("gcd(100,50): " + IntMath.gcd(100,50)); System.out.println("modulus(100,50): " + IntMath.mod(100,50)); System.out.println("factorial(5): " + IntMath.factorial(5)); } }
验证结果
使用javac编译器编译类,如下所示 −
C:\Guava>javac GuavaTester.java
现在运行 GuavaTester 查看结果。
C:\Guava>java GuavaTester
查看结果。
Error: overflow 20 Error: mode was UNNECESSARY, but rounding was necessary Log2(2): 1 Log10(10): 1 sqrt(100): 10 gcd(100,50): 50 modulus(100,50): 0 factorial(5): 120