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
< ? php function addToArrayForm ( $ A , $ K ) { $ v = array ( ) ; $ ans = array ( ) ; $ rem = 0 ; $ i = 0 ; for ( $ i = count ( $ A ) - 1 ; $ i >= 0 ; $ i -- ) { $ my = $ A [ $ i ] + $ K % 10 + $ rem ; if ( $ my > 9 ) { $ rem = 1 ; array_push ( $ v , $ my % 10 ) ; } else { array_push ( $ v , $ my ) ; $ rem = 0 ; } $ K = floor ( $ K / 10 ) ; } while ( $ K > 0 ) { $ my = $ K % 10 + $ rem ; array_push ( $ v , $ my % 10 ) ; if ( $ my / 10 > 0 ) $ rem = 1 ; else $ rem = 0 ; $ K = floor ( $ K / 10 ) ; } if ( $ rem > 0 ) array_push ( $ v , $ rem ) ; for ( $ i = count ( $ v ) - 1 ; $ i >= 0 ; $ i -- ) array_push ( $ ans , $ v [ $ i ] ) ; return $ ans ; } $ A = array ( 2 , 7 , 4 ) ; $ K = 181 ; $ ans = addToArrayForm ( $ A , $ K ) ; for ( $ i = 0 ; $ i < count ( $ ans ) ; $ i ++ ) echo $ ans [ $ i ] ; ? >