text: Sum of two numbers where one number is represented as array of digits | C ++ implementation of the approach ; Function to return the vector containing the answer ; Vector v is to store each digits sum and vector 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > addToArrayForm ( vector < int > & A , int K ) { vector < int > v , ans ; int rem = 0 ; int i = 0 ; for ( i = A . size ( ) - 1 ; i >= 0 ; i -- ) { int my = A [ i ] + K % 10 + rem ; if ( my > 9 ) { rem = 1 ; v . push_back ( my % 10 ) ; } else { v . push_back ( my ) ; rem = 0 ; } K = K / 10 ; } while ( K > 0 ) { int my = K % 10 + rem ; v . push_back ( my % 10 ) ; if ( my / 10 > 0 ) rem = 1 ; else rem = 0 ; K = K / 10 ; } if ( rem > 0 ) v . push_back ( rem ) ; for ( int i = v . size ( ) - 1 ; i >= 0 ; i -- ) ans . push_back ( v [ i ] ) ; return ans ; } int main ( ) { vector < int > A { 2 , 7 , 4 } ; int K = 181 ; vector < int > ans = addToArrayForm ( A , K ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] ; return 0 ; }