超长正数相加

Posted dongma

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了超长正数相加相关的知识,希望对你有一定的参考价值。

输入两个字符串数字,输出相加后的结果,string型

private static void AddLongInteger(String one,String two) {
int oneLen = one.length();
int twoLen = two.length();
int[] oneArr = new int[oneLen];
int[] twoArr = new int[twoLen];
int[] result = new int[oneLen > twoLen ? oneLen + 1 : twoLen + 1];
char[] oneChars = one.toCharArray();
char[] twoChars = two.toCharArray();
for (int i = 0; i < oneChars.length; i++) {
oneArr[i] = oneChars[i] - ‘0‘;
}
for (int i = 0; i < twoChars.length; i++) {
twoArr[i] = twoChars[i] - ‘0‘;
}
int oneIndex = oneArr.length - 1;
int twoIndex = twoArr.length - 1;
int index = result.length - 1;
while (oneIndex >=0 && twoIndex >= 0){
result[index] += oneArr[oneIndex] + twoArr[twoIndex];
if(result[index] > 9){
result[index] = result[index] % 10;
result[index-1] = 1;
}
oneIndex--;
twoIndex--;
index--;
}

while (oneIndex >=0){
result[index] += oneArr[oneIndex];
if(result[index] > 9){
result[index] = result[index] % 10;
result[index-1] = 1;
}
index--;
oneIndex--;
}
while (twoIndex >=0){
result[index] += twoArr[twoIndex];
if(result[index] > 9){
result[index] = result[index] % 10;
result[index-1] = 1;
}
index--;
twoIndex--;
}

System.out.println(Arrays.toString(result));
}

 

以上是关于超长正数相加的主要内容,如果未能解决你的问题,请参考以下文章

每日一题 | day17(杨辉三角的变形 |超长正整数相加)

华为OJ平台——超长正整数相加

两个超长字符串相加

超长正整数相加, BigInteger, 华为

算法算法求出2个超大正数相加

超长数运算