Problem Summary
Given a string of integers, whose first character is not zero, find the sum of all substrings.
Solution
Let S be the given string and N be its length.
Let f[i] be the sum of substrings that ends at S[i]. For any positive i, there are two cases. One is S[i], the other is S[j…i] ( j < i). The sums of these two cases are respectively S[i] - ‘0’ and f[i-1] × 10 + i × (S[i] - ‘0’).
So we have
f[0] = S[0] - ‘0’
f[i] = f[i-1] × 10 + (i+1) × (S[i] - ‘0’) , for i = 1,2,…,N-1
The answer is the sum of f[0],f[1],…,f[N-1].
Code
|
|