Java 如何将一个非常大的数字分配给BigInteger?
考虑到以下输入:Java 如何将一个非常大的数字分配给BigInteger?,java,biginteger,value-of,Java,Biginteger,Value Of,考虑到以下输入: 4534534534564657652349234230947234723947234234823048230957349573209483057 12324000123123 我尝试用以下方式将这些值分配给biginger public static void main(String[] args) { Scanner sc = new Scanner(System.in); BigInteger num1 = BigInteger.val
4534534534564657652349234230947234723947234234823048230957349573209483057
12324000123123
我尝试用以下方式将这些值分配给biginger
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger num1 = BigInteger.valueOf(sc.nextLong());
sc.nextLine();
BigInteger num2 = BigInteger.valueOf(sc.nextLong());
BigInteger additionTotal = num1.add(num2);
BigInteger multiplyTotal = num1.multiply(num2);
System.out.println(additionTotal);
System.out.println(multiplyTotal);
}
第一个值在一个长数字的边界之外,因此我得到以下异常:
线程“main”java.util.InputMismatchException中的异常:用于输入
字符串:
“4534564657652349234230947234723947234234823048230957349573209483057”
我假设BigInteger需要一个长类型与
valueOf()
方法一起使用(如上所述)。如何将非常大的数字传递给BigInteger?当输入的数字不适合long
,:
使用字符串构造函数 像这样
如果长数据类型可以处理任意大的数字,则不需要BigInteger。使用字符串构造函数:
以字符串形式读取中的巨大数字
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
BigInteger num1 = new BigInteger(s);
s = in.nextLine();
BigInteger num2 = new BigInteger(s);
//do stuff with num1 and num2 here
}
public BigInteger(String val)
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
BigInteger num1 = new BigInteger(s);
s = in.nextLine();
BigInteger num2 = new BigInteger(s);
//do stuff with num1 and num2 here
}