https://blog.csdn.net/xujunabc999/article/details/47374303
https://www.cnblogs.com/maydow/p/4782482.html
解法1:使用java自带的BigDecimal类
import java.math.BigDecimal; import java.util.Scanner; public class test1 { public static void main(String[] args) { String s1="123456789123456789"; String s2="123456789123456789"; BigDecimal bigDecimal=new BigDecimal(s1); BigDecimal bigDecimal1=new BigDecimal(s2); BigDecimal add = bigDecimal.add(bigDecimal1); System.out.println(add); } }
解法2:
按照正常的加法运算,相加进位的方式。使用StringBuilder存储我们相加的结果。
import java.math.BigDecimal; import java.util.Scanner; public class test1 { public static void main(String[] args) { String t1 = "123456789123456789"; String t2 = "123456789123456789"; System.out.println(getStr(t1, t2)); } public static String getStr(String a, String b) { int l = a.length(); int s = b.length(); String longString = l > s ? a : b; String shortString = l <= s ? a : b; l = longString.length(); s = shortString.length(); longString = new StringBuilder(longString).reverse().toString(); shortString = new StringBuilder(shortString).reverse().toString(); StringBuilder stringBuilder = new StringBuilder(); boolean carry = false; for (int i = 0; i < s; i++) { char cl = longString.charAt(i); char cs = shortString.charAt(i); int il = cl - '0'; int is = cs - '0'; int nx = il + is + (carry ? 1 : 0); if (nx > 9) { carry = true; stringBuilder.append((char) ('0' + nx - 10)); } else { carry = false; stringBuilder.append((char) ('0' + nx)); } } if (s == l && carry) { stringBuilder.append('1'); return stringBuilder.toString(); } String str = longString.substring(s, l); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); int nx = c - '0' + (carry ? 1 : 0); if (nx > 9) { carry = true; stringBuilder.append((char) ('0' + nx - 10)); } else { carry = false; stringBuilder.append((char) ('0' + nx)); } } if (carry) stringBuilder.append('1'); return stringBuilder.reverse().toString(); } }