Sum of all substrings of a string representing a number | Set 1 | Java program to print sum of all subString of a number represented as a String ; Utility method to convert character digit to integer digit ; Returns sum of all subString of num ; Storing prev value ; SubStrings sum upto current index loop over all digits of String ; Update each sumofdigit from previous value ; Add current value to the result ; Update previous ; Driver code to test above methods
import java . util . * ; class GFG { static int toDigit ( char ch ) { return ( ch - '0' ) ; } static int sumOfSubStrings ( String num ) { int n = num . length ( ) ; int prev = toDigit ( num . charAt ( 0 ) ) ; int res = prev ; int current = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit ( num . charAt ( i ) ) ; current = ( i + 1 ) * numi + 10 * prev ; res += current ; prev = current ; } return res ; } public static void main ( String [ ] args ) { String num = "1234" ; System . out . print ( sumOfSubStrings ( num ) + "NEW_LINE"); } }