Program to find total sum of all substrings of a number given as string in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number in string format, and we have to find the sum of all substrings of s. The answer may be very large, so return result modulo 10^9+7.

So, if the input is like s = "268", then the output will be 378 as the substrings are "2", "6", "8", "26", "68" and "268" total sum is 378.

To solve this, we will follow these steps −

  • M := 10^9 + 7
  • sum_val := 0
  • B := 1
  • res := 0
  • for i in range size of s - 1 down to 0, decrease by 1, do
    • res :=(res + digit value of s[i] * B *(i + 1)) mod M
    • sum_val := sum_val - digit value of s[i]
    • B := (B * 10 + 1) mod M
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(s):
   M = 10 ** 9 + 7
   sum_val = 0
   B = 1
   res = 0
   for i in range(len(s) - 1, -1, -1):
      res = (res + int(s[i]) * B * (i + 1)) % M
      sum_val -= int(s[i])
      B = (B * 10 + 1) % M
   return res

s = "268"
print(solve(s))

Input

"268"

Output

378
raja
Published on 07-Oct-2021 12:36:02
Advertisements