Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying the three factors as explained above . s [ i ] - '0' is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver Code
function sumOfSubstrings ( num ) { let sum = 0 ; let mf = 1 ; for ( let i = num . length - 1 ; i >= 0 ; i -- ) { sum += ( num [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } let num = " " ; document . write ( sumOfSubstrings ( num ) ) ;