用代码实现两个超大数相加,要求函数或方法输入两个任意长度(长度可能超过所有基础类型表示的范围)的数值,能计算并输出结果
@Test
public void testBig() {
System.out.println(bigAdd("123456789", "9999999999999999999999999"));
}
public static String bigAdd(String a, String b) {
char[] charsA = new StringBuilder(a).reverse().toString().toCharArray();
char[] charsB = new StringBuilder(b).reverse().toString().toCharArray();
int maxLength = Math.max(charsA.length, charsB.length);
int[] result = new int[maxLength + 1];
int temp = 0;
for (int i = 0; i <= maxLength; i++) {
temp = result[i];
if (i < charsA.length) {
temp += charsA[i] - '0';
}
if (i < charsB.length) {
temp += charsB[i] - '0';
}
if (temp >= 10) {
temp -= 10;
result[i + 1] = 1;
}
result[i] = temp;
}
StringBuilder sb = new StringBuilder();
boolean flag = true;
for (int i = maxLength; i >= 0; i--) {
if (result[i] == 0 && flag) {
continue;
}
flag = false;
sb.append(result[i]);
}
return sb.toString();
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。