Sum of two numbers where one number is represented as array of digits | 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
function addToArrayForm ( A , K ) { let v = [ ] ; let ans = [ ] ; let rem = 0 ; let i = 0 ; for ( i = A . length - 1 ; i >= 0 ; i -- ) { let my = A [ i ] + K % 10 + rem ; if ( my > 9 ) { rem = 1 ; v . push ( my % 10 ) ; } else { v . push ( my ) ; rem = 0 ; } K = parseInt ( K / 10 , 10 ) ; } while ( K > 0 ) { let my = K % 10 + rem ; v . push ( my % 10 ) ; if ( parseInt ( my / 10 , 10 ) > 0 ) rem = 1 ; else rem = 0 ; K = parseInt ( K / 10 , 10 ) ; } if ( rem > 0 ) v . push ( rem ) ; for ( let j = v . length - 1 ; j >= 0 ; j -- ) ans . push ( v [ j ] ) ; return ans ; } let A = [ ] ; A . push ( 2 ) ; A . push ( 7 ) ; A . push ( 4 ) ; let K = 181 ; let ans = addToArrayForm ( A , K ) ; for ( let i = 0 ; i < ans . length ; i ++ ) document . write ( ans [ i ] ) ;