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 ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute sum of current digits and carry ; Add remaining digits of str2 [ ] ; Add remaining carry ; reverse resultant string ; Driver code
< ? php function findSum ( $ str1 , $ str2 ) { if ( strlen ( $ str1 ) > strlen ( $ str2 ) ) { $ temp = $ str1 ; $ str1 = $ str2 ; $ str2 = $ temp ; } $ str3 = " " ; $ n1 = strlen ( $ str1 ) ; $ n2 = strlen ( $ str2 ) ; $ diff = $ n2 - $ n1 ; $ carry = 0 ; for ( $ i = $ n1 - 1 ; $ i >= 0 ; $ i -- ) { $ sum = ( ( ord ( $ str1 [ $ i ] ) - ord ( '0' ) ) + ( ( ord ( $ str2 [ $ i + $ diff ] ) - ord ( '0' ) ) ) + $ carry ) ; $ str3 . = chr ( $ sum % 10 + ord ( '0' ) ) ; $ carry = ( int ) ( $ sum / 10 ) ; } for ( $ i = $ n2 - $ n1 - 1 ; $ i >= 0 ; $ i -- ) { $ sum = ( ( ord ( $ str2 [ $ i ] ) - ord ( '0' ) ) + $ carry ) ; $ str3 . = chr ( $ sum % 10 + ord ( '0' ) ) ; $ carry = ( int ) ( $ sum / 10 ) ; } if ( $ carry ) $ str3 . = chr ( $ carry + ord ( '0' ) ) ; return strrev ( $ str3 ) ; } $ str1 = "12" ; $ str2 = "198111" ; print ( findSum ( $ str1 , $ str2 ) ) ; ? >