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 ; Function call
function isSmaller ( str1 , str2 ) { let n1 = str1 . length , n2 = str2 . length ; if ( n1 < n2 ) return true ; if ( n2 < n1 ) return false ; for ( let i = 0 ; i < n1 ; i ++ ) { if ( str1 [ i ] . charCodeAt ( ) < str2 [ i ] . charCodeAt ( ) ) return true ; else if ( str1 [ i ] . charCodeAt ( ) > str2 [ i ] . charCodeAt ( ) ) return false ; } return false ; } function findDiff ( str1 , str2 ) { if ( isSmaller ( str1 , str2 ) ) { let t = str1 ; str1 = str2 ; str2 = t ; } let str = " " ; let n1 = str1 . length , n2 = str2 . length ; let diff = n1 - n2 ; let carry = 0 ; for ( let i = n2 - 1 ; i >= 0 ; i -- ) { let sub = ( ( str1 [ i + diff ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) - ( str2 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) - carry ) ; if ( sub < 0 ) { sub = sub + 10 ; carry = 1 ; } else carry = 0 ; str += sub . toString ( ) ; } for ( let i = n1 - n2 - 1 ; i >= 0 ; i -- ) { if ( str1 [ i ] == ' ' && carry > 0 ) { str += " " ; continue ; } let sub = ( ( str1 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) - carry ) ; str += sub . toString ( ) ; carry = 0 ; } let aa = str . split ( ' ' ) ; aa . reverse ( ) ; return aa . join ( " " ) ; } let str1 = " " ; let str2 = " " ; document . write ( findDiff ( str1 , str2 ) ) ;