Java中的 BigInteger compareTo() 方法
Java.math.BigInteger.compareTo(BigInteger value)方法将此 BigInteger 与作为参数传递的 BigInteger 进行比较。
句法:
public int compareTo(BigInteger val)
参数:此方法接受一个强制参数val ,它是 BigInteger 与 BigInteger 对象进行比较。
返回:此方法返回以下内容:
- 0 :如果此 BigInteger 的值等于作为参数传递的 BigInteger 对象的值。
- 1 :如果此 BigInteger 的值大于作为参数传递的 BigInteger 对象的值。
- -1 :如果此 BigInteger 的值小于作为参数传递的 BigInteger 对象的值。
例子:
Input: BigInteger1=2345, BigInteger2=7456
Output: -1
Explanation: BigInteger1.compareTo(BigInteger2)=-1.
Input: BigInteger1=9834, BigInteger2=7456
Output: 1
Explanation: BigInteger1.compareTo(BigInteger2)=1.
示例 1:下面的程序说明了 BigInteger 类的 compareTo() 方法,当两个 BigInteger 相等时
// Java program to demonstrate
// compareTo() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("321456");
b2 = new BigInteger("321456");
// apply compareTo() method
int comparevalue = b1.compareTo(b2);
// print result
if (comparevalue == 0) {
System.out.println("BigInteger1 "
+ b1 + " and BigInteger2 "
+ b2 + " are equal");
}
else if (comparevalue == 1) {
System.out.println("BigInteger1 " + b1 + "
is greater than BigInteger2 " + b2);
}
else {
System.out.println("BigInteger1 " + b1 + "
is lesser than BigInteger2 " + b2);
}
}
}
输出:
BigInteger1 321456 and BigInteger2 321456 are equal
示例 2:当 BigInteger1 大于 BigInteger2
// Java program to demonstrate
// compareTo() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("654321");
b2 = new BigInteger("321456");
// apply compareTo() method
int comparevalue = b1.compareTo(b2);
// print result
if (comparevalue == 0) {
System.out.println("BigInteger1 " + b1 + "
and BigInteger2 " + b2 + " are equal");
}
else if (comparevalue == 1) {
System.out.println("BigInteger1 " + b1 + "
is greater than BigInteger2 " + b2);
}
else {
System.out.println("BigInteger1 " + b1 + "
is lesser than BigInteger2 " + b2);
}
}
}
输出:
BigInteger1 654321 is greater than BigInteger2 321456
示例 3:当 BigInteger1 小于 BigInteger2
// Java program to demonstrate
// compareTo() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Creating 2 BigInteger objects
BigInteger b1, b2;
b1 = new BigInteger("321456");
b2 = new BigInteger("564321");
// apply compareTo() method
int comparevalue = b1.compareTo(b2);
// print result
if (comparevalue == 0) {
System.out.println("BigInteger1 " + b1 + "
and BigInteger2 " + b2 + " are equal");
}
else if (comparevalue == 1) {
System.out.println("BigInteger1 " + b1 + "
is greater than BigInteger2 " + b2);
}
else {
System.out.println("BigInteger1 " + b1 + "
is lesser than BigInteger2 " + b2);
}
}
}
输出:
BigInteger1 321456 is lesser than BigInteger2 564321
参考:
BigInteger CompareTo() 文档