[Solved] How to add two int array values together?


This kinda works. I can think of a couple of cases where something like this would break, like if the arrays were like {9,9,9} and {9,9,9}, result would be {9,9,8} instead of {1,9,9,8}. It’s a minor fix that is being left as an activity to the reader.

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)); 
 }

solved How to add two int array values together?