因此,当不需要携带任何东西时,我已经正确添加了这两个数组。所以a [0,1,1] + b [0,1,1]会给我c [0,0,2,2],但是如果我同样做a [0,9,9] + b [0, 9,9]我只得到c [0,0,8,8]。方法addBigInts中的循环似乎无法按我认为的方式工作。任何想法表示赞赏。

import java.util.*;

public class AddBigInts {

public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    //init firstNum array
    int[] firstNum = new int[getDigit()];
    System.out.println("First number:");
    //gets input to pop array
    firstNum = getInt(firstNum);
    //second array is same length
    int[] secondNum = new int[firstNum.length];
    System.out.println("Second number:");
    //pop second array
    secondNum = getInt(secondNum);
    System.out.println(Arrays.toString(firstNum));
    System.out.println(Arrays.toString(secondNum));
    addBigInts(firstNum, secondNum);
}

//creates array that is one place bigger than entered #
public static int getDigit (){
    Scanner console = new Scanner(System.in);
    System.out.print("How many digits? ");
    int arraySize = console.nextInt();
    return arraySize + 1;
}

//populates array
public static int[] getInt (int[] num){
    Scanner console = new Scanner(System.in);
    for (int i=num.length-1; i>0; i--){
        System.out.print("Digit " + i + ": ");
        num[i] = console.nextInt();
    }
    return num;

}

//adds both arrays by index into the sum array
public static int[] addBigInts (int[]numArray1, int[] numArray2){
    int count = Math.max(numArray1.length, numArray2.length);
    int[] sum = new int[count+1];
    //starting at numArray1 & 2 index, sums ints
    for (int i=count-1; i>=0; i--){
        //sum has to be +1 for numArray1 & 2 indexes
        sum[i+1] = numArray1[i] + numArray2[i];
        if (sum[i+1]>9){
            //this line below doesn't seem to execute
            sum[i]++;
            sum[i+1] = sum[i+1] - 10;
        }
        else;

        }
    System.out.println(Arrays.toString(sum));
    return sum;
    }
}

最佳答案

你有:

sum[i+1] = numArray1[i] + numArray2[i];


你需要:

sum[i+1] += numArray1[i] + numArray2[i];


通过分配而不是添加,您将覆盖前一位的进位1。

10-08 02:07