Add two numbers represented by two arrays | Return sum of two number represented by the arrays . Size of a [ ] is greater than b [ ] . It is made sure be the wrapper function ; array to store sum . ; Until we reach beginning of array . we are comparing only for second array because we have already compare the size of array in wrapper function . ; find sum of corresponding element of both array . ; Finding carry for next sum . ; If second array size is less than the first array size . ; Add carry to first array elements . ; If there is carry on adding 0 index elements . append 1 to total sum . ; Converting array into number . ; Wrapper Function ; Making first array which have greater number of element ; Driven Code
< ? php function calSumUtil ( $ a , $ b , $ n , $ m ) { $ sum = array ( ) ; $ i = $ n - 1 ; $ j = $ m - 1 ; $ k = $ n - 1 ; $ carry = 0 ; $ s = 0 ; while ( $ j >= 0 ) { $ s = $ a [ $ i ] + $ b [ $ j ] + $ carry ; $ sum [ $ k ] = ( $ s % 10 ) ; $ carry = $ s / 10 ; $ k -- ; $ i -- ; $ j -- ; } while ( $ i >= 0 ) { $ s = $ a [ $ i ] + $ carry ; $ sum [ $ k ] = ( $ s % 10 ) ; $ carry = $ s / 10 ; $ i -- ; $ k -- ; } $ ans = 0 ; if ( $ carry ) $ ans = 10 ; for ( $ i = 0 ; $ i <= $ n - 1 ; $ i ++ ) { $ ans += $ sum [ $ i ] ; $ ans *= 10 ; } return $ ans / 10 ; } function calSum ( $ a , $ b , $ n , $ m ) { if ( $ n >= $ m ) return calSumUtil ( $ a , $ b , $ n , $ m ) ; else return calSumUtil ( $ b , $ a , $ m , $ n ) ; } $ a = array ( 9 , 3 , 9 ) ; $ b = array ( 6 , 1 ) ; $ n = count ( $ a ) ; $ m = count ( $ b ) ; echo calSum ( $ a , $ b , $ n , $ m ) ; ? >