Given a binary string str of length N, the task is to find the count of substrings of str which are divisible by 2. Leading zeros in a substring is allowed.
Input: str = “101”
“0” and “10” are the only substrings
which are divisible by 2.
Input: str = “10010”
Naive approach: A naive approach will be to generate all possible substrings and check if they are divisible by 2. The time complexity for this will be O(N3).
Efficient approach: It can be observed that any binary number is divisible by 2 only if it ends with a 0. Now, the task is to just count the number of substrings ending with 0. So, for every index i such that str[i] = ‘0’, find the number of substrings ending at i. This value is equal to (i + 1) (0-based indexing). Thus, the final answer will be equal to the summation of (i + 1) for all i such that str[i] = ‘0’.
Below is the implementation of the above approach:
- Number of substrings divisible by 4 in a string of integers
- Number of substrings divisible by 6 in a string of integers
- Number of substrings with odd decimal value in a binary string
- Split the binary string into substrings with equal number of 0s and 1s
- Given a binary string, count number of substrings that start and end with 1.
- Number of subsequences in a given binary string divisible by 2
- Number of sub-sequences of non-zero length of a binary string divisible by 3
- Number of substrings divisible by 8 but not by 3
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
- Count of substrings of a binary string containing K ones
- Counting even decimal value substrings in a binary string
- Number of substrings of a string
- Largest sub-string of a binary string divisible by 2
- Number of substrings of one string present in other
- Sum of all substrings of a string representing a number | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.