Sum of two numbers where one number is represented as array of digits | 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
def addToArrayForm ( A , K ) : NEW_LINE INDENT v , ans = [ ] , [ ] NEW_LINE rem , i = 0 , 0 NEW_LINE for i in range ( len ( A ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT my = A [ i ] + ( K % 10 ) + rem NEW_LINE if my > 9 : NEW_LINE INDENT rem = 1 NEW_LINE v . append ( my % 10 ) NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( my ) NEW_LINE rem = 0 NEW_LINE DEDENT K = K // 10 NEW_LINE DEDENT while K > 0 : NEW_LINE INDENT my = ( K % 10 ) + rem NEW_LINE v . append ( my % 10 ) NEW_LINE if my // 10 > 0 : NEW_LINE INDENT rem = 1 NEW_LINE DEDENT else : NEW_LINE INDENT rem = 0 NEW_LINE DEDENT K = K // 10 NEW_LINE DEDENT if rem > 0 : NEW_LINE INDENT v . append ( rem ) NEW_LINE DEDENT for i in range ( len ( v ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT ans . append ( v [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 2 , 7 , 4 ] NEW_LINE K = 181 NEW_LINE ans = addToArrayForm ( A , K ) NEW_LINE for i in range ( 0 , len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " " ) NEW_LINE DEDENT DEDENT