Sum of all possible strings obtained by removal of non | Java 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
import java . util . * ; class GFG { static int N = 10 ; static int [ ] pref = new int [ N ] ; static int [ ] power = new int [ N ] ; static int toDigit ( char ch ) { return ( ch - '0' ) ; } static void powerOf10 ( ) { power [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) power [ i ] = power [ i - 1 ] * 10 ; } static void precomputePrefix ( char [ ] str , int n ) { pref [ 0 ] = str [ 0 ] - '0' ; for ( int i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + toDigit ( str [ i ] ) ; } static int triangularNumber ( int i ) { int res = i * ( i + 1 ) / 2 ; return res ; } static int sumOfSubStrings ( String str ) { int n = str . length ( ) ; powerOf10 ( ) ; precomputePrefix ( str . toCharArray ( ) , n ) ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans += ( pref [ n - i - 2 ] * ( i + 1 ) + toDigit ( str . charAt ( n - i - 1 ) ) * triangularNumber ( n - i - 1 ) ) * power [ i ] ; } return ans ; } public static void main ( String [ ] args ) { String str = "1234" ; System . out . print ( sumOfSubStrings ( str ) ) ; } }