Skip to content

Commit de1440b

Browse files
Create Substrings_with_1.py
1 parent c78c70c commit de1440b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Math/Substrings_with_1.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''Name : Abhinav kumar
2+
Github username : Abhinavcode13
3+
Repository name : data-structures-and-algorithms
4+
Problem : Number of Substrings With Only 1s in Python
5+
Issue Number : #518
6+
Problem statement :
7+
8+
Explanation of the below Python code :
9+
10+
The implementation is quite similar to the C++ implementation. We iterate over the string s using a for loop and keep track of the count of consecutive 1's using the variable count. Whenever we encounter a '0', we calculate the number of substrings that can be formed using the formula n*(n+1)/2, add it to the final answer ans, and reset the value of count to 0. Finally, we calculate the number of substrings for the last substring of consecutive 1's, add it to the final answer ans, and return the result modulo 10^9 + 7. Note that we have used the integer division operator // to perform the division in Python.
11+
12+
13+
14+
'''
15+
16+
----------------------------------------------------------------------------------------------//Python code begins here--------------------------------------------------------------------------------------------------------------------------------------
17+
18+
class Solution:
19+
def numSub(self, s: str) -> int:
20+
count = 0
21+
ans = 0
22+
for i in range(len(s)):
23+
if s[i] == '1':
24+
count += 1
25+
else:
26+
ans = (ans + (count*(count+1))//2) % (10**9 + 7)
27+
count = 0
28+
ans = (ans + (count*(count+1))//2) % (10**9 + 7)
29+
return ans

0 commit comments

Comments
 (0)