📜  Java中的 BigInteger intValue() 方法

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

Java中的 BigInteger intValue() 方法

Java.math.BigInteger.intValue()将此 BigInteger 转换为整数值。如果此函数返回的值太大而无法放入整数值,则它将仅返回低 32 位。此外,这种转换可能会丢失有关 BigInteger 值整体大小的信息。该方法也可以返回符号相反的结果。

句法:

public int intValue()

返回:该方法返回一个 int 值,该值表示此 BigInteger 的整数值。

例子:

Input: BigInteger1=32145
Output: 32145
Explanation: BigInteger1.intValue()=32145.

Input: BigInteger1=4326516236135
Output: 1484169063
Explanation: BigInteger1.intValue()=1484169063. This BigInteger is too big for 
intValue so it is returning lower 32 bit.

示例 1:以下程序说明 BigInteger 类的 intValue() 方法

// Java program to demonstrate 
// intValue() 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("32145");
        b2 = new BigInteger("7613721");
  
        // apply intValue() method
        int intValueOfb1 = b1.intValue();
        int intValueOfb2 = b2.intValue();
  
        // print intValue
        System.out.println("intValue of "
                           + b1 + " : " + intValueOfb1);
        System.out.println("intValue of "
                           + b2 + " : " + intValueOfb2);
    }
}
输出:
intValue of 32145 : 32145
intValue of 7613721 : 7613721

示例 2:当返回整数对于 int 值来说太大时。

// Java program to demonstrate 
// intValue() 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("4326516236135");
        b2 = new BigInteger("251362466336");
  
        // apply intValue() method
        int intValueOfb1 = b1.intValue();
        int intValueOfb2 = b2.intValue();
  
        // print intValue
        System.out.println("intValue of "
                           + b1 + " : " + intValueOfb1);
        System.out.println("intValue of "
                           + b2 + " : " + intValueOfb2);
    }
}
输出:
intValue of 4326516236135 : 1484169063
intValue of 251362466336 : -2040604128

参考:
BigInteger intValue() 文档