Suppose we have a binary string s. We have to find the number of substrings with all characters 1's. The answer may be very large so return result mod 10^9 + 7.
So, if the input is like s = "1011010", then the output will be 5 because 1. four times "1" 2. one time "11"
To solve this, we will follow these steps −
m := 10^9+7
result := 0
div := divide the binary string by splitting it using '0'
for each x in div, do
if x is empty, then go for next iteration
result := result + quotient of (size of x *(size of x +1))/2
return result mod m
Let us see the following implementation to get better understanding −
Example
def solve(s): m = 10**9+7 result = 0 for x in s.split('0'): if not x: continue result += (len(x)*(len(x)+1)) // 2 return result % m s = "1011010" print(solve(s))
Input
"1011010"
Output
5