Difference of two large numbers | Returns true if str1 is smaller than str2 , else false . ; Calculate lengths of both string ; Function for finding difference of larger numbers ; Before proceeding further , make sure str1 is not smaller ; Take an empty string for storing result ; Calculate lengths of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute difference of current digits and carry ; subtract remaining digits of str1 [ ] ; if ( $i > 0 $sub > 0 ) remove preceding 0 's ; reverse resultant string ; Driver code ; Function call
< ? php function isSmaller ( $ str1 , $ str2 ) { $ n1 = strlen ( $ str1 ) ; $ n2 = strlen ( $ str2 ) ; if ( $ n1 < $ n2 ) return true ; if ( $ n2 < $ n1 ) return false ; for ( $ i = 0 ; $ i < $ n1 ; $ i ++ ) { if ( $ str1 [ $ i ] < $ str2 [ $ i ] ) return true ; else if ( $ str1 [ $ i ] > $ str2 [ $ i ] ) return false ; } return false ; } function findDiff ( $ str1 , $ str2 ) { if ( isSmaller ( $ str1 , $ str2 ) ) { $ t = $ str1 ; $ str1 = $ str2 ; $ str2 = $ t ; } $ str = " " ; $ n1 = strlen ( $ str1 ) ; $ n2 = strlen ( $ str2 ) ; $ diff = $ n1 - $ n2 ; $ carry = 0 ; for ( $ i = $ n2 - 1 ; $ i >= 0 ; $ i -- ) { $ sub = ( ( ord ( $ str1 [ $ i + $ diff ] ) - ord ( '0' ) ) - ( ord ( $ str2 [ $ i ] ) - ord ( '0' ) ) - $ carry ) ; if ( $ sub < 0 ) { $ sub = $ sub + 10 ; $ carry = 1 ; } else $ carry = 0 ; $ str . = chr ( $ sub + ord ( "0" ) ) ; } for ( $ i = $ n1 - $ n2 - 1 ; $ i >= 0 ; $ i -- ) { if ( $ str1 [ $ i ] == '0' && $ carry > 0 ) { $ str . = "9" ; continue ; } $ sub = ( ord ( $ str1 [ $ i ] ) - ord ( '0' ) - $ carry ) ; $ str . = chr ( $ sub + ord ( "0" ) ) ; $ carry = 0 ; } return strrev ( $ str ) ; } $ str1 = "88" ; $ str2 = "1079" ; print ( findDiff ( $ str1 , $ str2 ) ) ; ? >