Sum of two numbers where one number is represented as array of digits | Java implementation of the approach ; Function to return the vector containing the answer ; ArrayList v is to store each digits sum and ArrayList ans is to store the answer ; No carry in the beginning ; Start loop from the end and take element one by one ; Array index and last digit of number ; Maintain carry of summation ; Push the digit value into the array ; K value is greater then 0 ; Push digits of K one by one in the array ; Also maintain carry with summation ; Reverse the elements of vector v and store it in vector ans ; Driver code ; Print the answer
import java . util . * ; class GFG { static ArrayList < Integer > addToArrayForm ( ArrayList < Integer > A , int K ) { ArrayList < Integer > v = new ArrayList < Integer > ( ) ; ArrayList < Integer > ans = new ArrayList < Integer > ( ) ; int rem = 0 ; int i = 0 ; for ( i = A . size ( ) - 1 ; i >= 0 ; i -- ) { int my = A . get ( i ) + K % 10 + rem ; if ( my > 9 ) { rem = 1 ; v . add ( my % 10 ) ; } else { v . add ( my ) ; rem = 0 ; } K = K / 10 ; } while ( K > 0 ) { int my = K % 10 + rem ; v . add ( my % 10 ) ; if ( my / 10 > 0 ) rem = 1 ; else rem = 0 ; K = K / 10 ; } if ( rem > 0 ) v . add ( rem ) ; for ( int j = v . size ( ) - 1 ; j >= 0 ; j -- ) ans . add ( v . get ( j ) ) ; return ans ; } public static void main ( String [ ] args ) { ArrayList < Integer > A = new ArrayList < Integer > ( ) ; A . add ( 2 ) ; A . add ( 7 ) ; A . add ( 4 ) ; int K = 181 ; ArrayList < Integer > ans = addToArrayForm ( A , K ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) ) ; } }