Sum of all possible strings obtained by removal of non | JavaScript program for the above approach ; Function to convert a character to its equivalent digit ; Function to precompute powers of 10 ; Function to precompute prefix sum of numerical Strings ; Function to return the i - th term of Triangular Number ; Function to return the sum of all resulting Strings ; Precompute powers of 10 ; Precompute prefix sum ; Initialize result ; Apply the above general formula for every i ; Return the answer ; Driver Code ; Function Call
var N = 10 ; var pref = new Array ( N ) . fill ( 0 ) ; var power = new Array ( N ) . fill ( 0 ) ; function toDigit ( ch ) { return ch - " " ; } function powerOf10 ( ) { power [ 0 ] = 1 ; for ( var i = 1 ; i < N ; i ++ ) power [ i ] = power [ i - 1 ] * 10 ; } function precomputePrefix ( str , n ) { pref [ 0 ] = str [ 0 ] - " " ; for ( var i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + toDigit ( str [ i ] ) ; } function triangularNumber ( i ) { var res = parseInt ( ( i * ( i + 1 ) ) / 2 ) ; return res ; } function sumOfSubStrings ( str ) { var n = str . length ; powerOf10 ( ) ; precomputePrefix ( str . split ( " " ) , n ) ; var ans = 0 ; for ( var i = 0 ; i < n - 1 ; i ++ ) { ans += ( pref [ n - i - 2 ] * ( i + 1 ) + toDigit ( str [ n - i - 1 ] ) * triangularNumber ( n - i - 1 ) ) * power [ i ] ; } return ans ; } var str = " " ; document . write ( sumOfSubStrings ( str ) ) ;