java - How to add two int array values together? -


i trying add 2 int arrays sum. first array contains 0000000000000000123456789 , second array contains 0001111111111111111111111. sum should 1111111111111234567900. i'm trying without biginteger or 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;     }                    } 

the output produced @ moment 00011111111111112345678100. how can fix code 8 becomes 9?

this kinda works. can think of couple of cases break, if arrays {9,9,9} , {9,9,9}, result {9,9,8} instead of {1,9,9,8}. it's minor fix being left activity 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];     (int = number1.length - 1; >= 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));   } 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -