我尝试了下面的代码,但出现错误。我将如何将两个表示为字符串的大值添加在一起?
public class LargeAddition {
static String testcase1 = "987659876598765";
static String testcase2 = "9999999999999999999999999988888888888";//can we add this kind of large num
public static void main(String args[]){
LargeAddition testInstance = new LargeAddition();
String result = testInstance.add(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public String add(String str1, String str2){
Long num=000000000000000L;
//String str="";
num=Long.parseLong(str1)+Long.parseLong(str2);
//String str=num.toString();
return num.toString();
}
}
最佳答案
使用BigInteger
,Long
是这些值的缩写。
public static String add(String str1, String str2) {
BigInteger big1 = new BigInteger(str1);
BigInteger big2 = new BigInteger(str2);
final BigInteger num = big1.add(big2);
return num.toString();
}
关于java - 如何在 Java 中添加非常大的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21468857/