- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- Program to find number of substrings with only 1s using Python
- Count numbers have all 1s together in binary representation in C++
- Count Binary Substrings 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
- Program to count number of swaps required to group all 1s together in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- C# Program to find all substrings in a string
- Binary String With Substrings Representing 1 To N in C++
- Count all 0s which are blocked by 1s in binary matrix in C++
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Program to count number of palindromic substrings in Python
- Program to count number of homogenous substrings in Python
- Program to find all substrings whose anagrams are present in a string in Python
- Count of substrings of a binary string containing K ones in C++

Advertisements