Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | 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 . int ( s [ i ] ) is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver code to test above methods
def sumOfSubstrings ( num ) : NEW_LINE INDENT sum = 0 NEW_LINE INDENT mf = 1 NEW_LINE for i in range ( len ( num ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = sum + ( int ( num [ i ] ) ) * ( i + 1 ) * mf NEW_LINE mf = mf * 10 + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = "6759" NEW_LINE print ( sumOfSubstrings ( num ) ) NEW_LINE DEDENT