Sum of all substrings of a string representing a number | Set 1 | C ++ 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 ; prev = current ; update previous ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int toDigit ( char ch ) { return ( ch - '0' ) ; } int sumOfSubstrings ( string num ) { int n = num . length ( ) ; int prev = toDigit ( num [ 0 ] ) ; int res = prev ; int current = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit ( num [ i ] ) ; current = ( i + 1 ) * numi + 10 * prev ; res += current ; } return res ; } int main ( ) { string num = "1234" ; cout << sumOfSubstrings ( num ) << endl ; return 0 ; }