Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | C ++ program to print sum of all substring of a number represented as a string ; Returns sum of all substring of num ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSubstrings ( string num ) { long long int mf = 1 ; for ( int i = num . size ( ) - 1 ; i >= 0 ; i -- ) { sum += ( num [ i ] - '0' ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } int main ( ) { string num = "6759" ; cout << sumOfSubstrings ( num ) << endl ; return 0 ; }