Java BigInteger max()和min()方法

Java BigInteger max()和min()方法

  • BigInteger max() 方法 : BigInteger的max()方法返回当前BigInteger和作为参数传递给该方法的BigInteger中数值较大的那个。如果两个值都相等,可以返回其中一个。

在BigInteger类中也有一个类似的方法compareTo()。max()方法与compareTo()不同,在compareTo()方法中我们必须解释结果,而在max方法中,最大的BigInteger已经被返回。

语法:

public BigInteger max(BigInteger val)

参数: 该方法接受一个参数val,指的是要计算的最大值。

返回值:该方法返回BigInteger,其值为this和val中的较大值。如果它们相等,可以返回其中之一。

下面的程序说明了BigInteger类的max()方法。

/*
 *Program Demonstrate max() method of BigInteger 
*/
import java.math.*;
  
public class GFG {
  
   public static void main(String[] args) {
  
        
       // Create 2 BigInteger objects
      BigInteger biginteger=new BigInteger("8976543245");
      BigInteger val=new BigInteger("9248040402");
        
      // Call max() method to find greater value
      // between two BigIntegers.
      BigInteger biggerInteger = biginteger.max(val);
  
      String result = "Bigger Integer between "+biginteger+" and "
                      +val+ " is " +biggerInteger;
  
      // Prints the result 
      System.out.println(result);
     
   }
}

输出:

Bigger Integer between 8976543245 and 9248040402 is 9248040402
  • BigInteger min() 方法 : BigInteger的min()方法返回当前BigInteger和作为参数传递给方法的BigInteger之间较小的值。如果这两个数值相等,可以返回其中一个。

在BigInteger类中也有一个类似的方法compareTo()。min()方法与compareTo()不同,在compareTo()方法中我们必须解释结果,而在min()方法中,最小的BigInteger将被返回。

语法:

public BigInteger min(BigInteger val)

参数:该方法接受一个参数val,指的是要计算最小值的值。

返回值:该方法返回BigInteger,其值为this和val的较小值。如果这两个值相等,可以返回其中之一。

下面的程序说明了BigInteger类的min()方法。

/*
 *Program Demonstrate min() method of BigInteger 
*/
import java.math.*;
  
public class GFG {
  
   public static void main(String[] args) {
  
    // Create 2 BigInteger objects
      BigInteger biginteger=new BigInteger("5782539631");
      BigInteger val=new BigInteger("3592633823");
        
      // Call min() method to find lesser value
      // between two BigIntegers.
      BigInteger biggerInteger = biginteger.min(val);
  
      String result = "lesser Integer between "+biginteger+" and "
                      +val+ " is " +biggerInteger;
  
      // Prints the result 
      System.out.println(result);
     
   }
}

输出:

lesser Integer between 5782539631 and 3592633823 is 3592633823

参考资料
* https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#max(java.math.BigInteger)
* https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#min(java.math.BigInteger)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程