Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Reverse both of strings ; Do school mathematics , compute sum of current digits and carry ; Calculate carry for next step ; Add remaining digits of larger number ; Add remaining carry ; reverse resultant string ; Driver code
< ? php function findSum ( $ str1 , $ str2 ) { if ( strlen ( $ str1 ) > strlen ( $ str2 ) ) { $ t = $ str1 ; $ str1 = $ str2 ; $ str2 = $ t ; } $ str = " " ; $ n1 = strlen ( $ str1 ) ; $ n2 = strlen ( $ str2 ) ; $ str1 = strrev ( $ str1 ) ; $ str2 = strrev ( $ str2 ) ; $ carry = 0 ; for ( $ i = 0 ; $ i < $ n1 ; $ i ++ ) { $ sum = ( ( ord ( $ str1 [ $ i ] ) -48 ) + ( ( ord ( $ str2 [ $ i ] ) -48 ) + $ carry ) ) ; $ str . = chr ( $ sum % 10 + 48 ) ; $ carry = ( int ) ( $ sum / 10 ) ; } for ( $ i = $ n1 ; $ i < $ n2 ; $ i ++ ) { $ sum = ( ( ord ( $ str2 [ $ i ] ) -48 ) + $ carry ) ; $ str . = chr ( $ sum % 10 + 48 ) ; $ carry = ( int ) ( $ sum / 10 ) ; } if ( $ carry ) $ str . = chr ( $ carry + 48 ) ; $ str = strrev ( $ str ) ; return $ str ; } $ str1 = "12" ; $ str2 = "198111" ; echo findSum ( $ str1 , $ str2 ) ; ? >