Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Java program to print sum of all substring of a number represented as a string ; 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 to test above methods
import java . util . Arrays ; public class GFG { public static long sumOfSubstrings ( String num ) { long sum = 0 ; long mf = 1 ; for ( int i = num . length ( ) - 1 ; i >= 0 ; i -- ) { sum += ( num . charAt ( i ) - '0' ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } public static void main ( String [ ] args ) { String num = "6759" ; System . out . println ( sumOfSubstrings ( num ) ) ; } }