我正在尝试将两个int数组一起添加以获得总和。第一个数组包含0000000000000000123456789,第二个数组包含0001111111111111111111111。总和应为1111111111111234567900.此外,我尝试在没有BigInteger或BigDecimal的情况下执行此操作。
for(int i=0; i<number1.length;i++){
add= number1[i]+number2[i];
if(plus>=10){
sum[i-1]+=add/10;
sum[i] = add%10;
}else{
sum[i]=add;
}
}
此时产生的输出是00011111111111112345678100.如何修复我的代码以使8成为9?
答案 0 :(得分:1)
这种方式有效。我可以想到一些像这样的东西会破坏的情况,比如阵列就像{9,9,9}和{9,9,9},result
就是{9,9,8而不是{1,9,9,8}。 这是一个小修复,被留作读者的活动。
public static void main(String []args){
int[] number1 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9};
int[] number2 = {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int carry = 0, sum = 0;
int[] result = new int[number1.length];
for (int i = number1.length - 1; i >= 0 ; i--) {
sum = number1[i] + number2[i] + carry;
result[i] = sum%10;
carry = sum/10;
}
// [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 9, 0, 0]
System.out.println(Arrays.toString(result));
}
答案 1 :(得分:0)
此代码适用于正确携带大于10的数字到下一个数字并保留较低的数字!
int[] result = new int[number1.length+1];
for (int i=number1.length-1; i>=0;i--){
result[i+1] = number1[i] + number[i] + result[i+1];
if(result[i+1] >= 10){
result[i+1] -= 10; // it could never be more than 20 so this is ok and if it is 10 than it will still carry over to the next
result[i] = 1; // the ten carried to the next one
}
}
与Seek Addo的答案类似,但避免了他的代码中发现的错误,这些错误阻止了应用程序正确携带数字。
这是我能想到的最紧凑的方式,并且应该得到
的正确答案[1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,9,0,0]或1111111111111234567900
答案 2 :(得分:0)
试试这个
int[] number = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9};
int[] number2 = {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] result = new int[number.length+1];
int carry = 0;
for (int i = number.length - 1; i >= 0; i--) {
result[i+1] = number[i] + number2[i] + carry;
if (result[i+1] > 9) {
carry = result[i+1] - 9;
result[i+1] -= 10;
}
else {
carry = 0;
}
}
System.out.println(Arrays.toString(result));
答案 3 :(得分:0)
接受的答案并不好。这是我的版本(支持不同的数组大小):
public static int[] sumIntArrays(int[] n1, int[] n2) {
int n1Size = n1.length - 1, n2Size = n2.length - 1, indexSum = n1Size > n2Size ? n1Size + 2 : n2Size + 2, slack = 0, s;
int[] sum = new int[indexSum];
while (true) {
if (n1Size < 0 && n2Size < 0)
break;
s = (n1Size < 0 ? 0 : n1[n1Size--]) + (n2Size < 0 ? 0 : n2[n2Size--]) + slack;
if (s > 9) {
sum[--indexSum] = s % 10;
slack = s / 10;
} else {
sum[--indexSum] = s;
slack = 0;
}
}
if (slack != 0)
sum[0] = slack;
return sum;
}