- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to count substrings with all 1s in binary string in Python

Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.

So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]

To solve this, we will follow these steps −

- a := 0
- count := 0
- for i in range 0 to size of s - 1, do
- if s[i] is same as "0", then
- a := 0

- otherwise,
- a := a + 1
- count := count + a

- if s[i] is same as "0", then
- return count

## Example

Let us see the following implementation to get better understanding −

def solve(s): a = 0 count = 0 for i in range(len(s)): if s[i] == "0": a = 0 else: a += 1 count += a return count s = "100111" print(solve(s))

## Input

"100111"

## Output

7

- Related Questions & Answers
- Program to find number of substrings with only 1s using Python
- Count Binary Substrings in C++
- Count numbers have all 1s together in binary representation in C++
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Maximum size rectangle binary sub-matrix with all 1s in C++ Program
- C# Program to find all substrings in a string
- Program to count number of swaps required to group all 1s together in Python
- Binary String With Substrings Representing 1 To N in C++
- Count all 0s which are blocked by 1s in binary matrix in C++
- Check if all the 1s in a binary string are equidistant or not in Python
- Program to count number of palindromic substrings in Python
- Program to count number of homogenous substrings in Python
- Count of substrings of a binary string containing K ones in C++
- Maximum size rectangle binary sub-matrix with all 1s in C++
- Program to find all substrings whose anagrams are present in a string in Python

Advertisements