原文链接:https://www.cnblogs.com/socrates-lzstu/p/6774682.html
案例:本文主要描述Java两个大字符串数字相加,有两个字符串数字,数字特别大,数字超出了Integer相加的范围,直接相加的会有溢出
一、首先创建一个maven工程,配置依赖包
无特殊依赖
二、开始写入自动化测试代码
public class TestStringAdd {
public static void main(String[] args) {
String str1="568658123123312123123123123123131233132123123123131231233123131231231231231";
String str2="132121231231231312312312312312312312312312312312313123123132";
StringBuffer s1 = new StringBuffer(str1).reverse();
StringBuffer s2 = new StringBuffer(str2).reverse();
StringBuffer res = new StringBuffer();
int len1 = s1.length();
int len2 = s2.length();
int len;
if (len1 < len2) {
len = len2;
int count = len2 - len1;
while (count-- > 0)
s1.append('0');
} else {
len = len1;
int count = len1 - len2;
while (count-- > 0)
s2.append('0');
}
int overflow = 0;
int num;
for (int i = 0; i < len; i++) {
num = s1.charAt(i) - '0' + s2.charAt(i) - '0' + overflow;
if (num >= 10) {
overflow = 1;
num -= 10;
} else {
overflow = 0;
}
res.append(String.valueOf(num));
}
if (overflow == 1)
res.append(1);
System.out.println(res.reverse().toString());
}
}
三、运行结果
568658123123312255244354354354443545444435435435443543545435443544354354363