- Related Questions & Answers
- Sorting binary string having an even decimal value using JavaScript
- Counting matching substrings in JavaScript
- Counting Maximal Value Roots in Binary Tree in C++
- Maximum decimal value path in a binary matrix in C++
- Count Binary Substrings in C++
- Binary String With Substrings Representing 1 To N in C++
- Count of substrings of a binary string containing K ones in C++
- Counting substrings of a string that contains only one distinct letter in JavaScript
- Find all substrings in a string using C#
- Counting numbers after decimal point in JavaScript
- Binary to decimal using C#
- Unique Substrings in Wraparound String in C++
- Replacing Substrings in a Java String
- C# Program to find all substrings in a string
- Convert a stored MD5 string to a decimal value in MySQL?

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

We are given with a string of 0’s and 1’s only. The string represents a binary number read from left to right. i.e. 001 is 4 and not 1. The goal is to find all substrings that represent an even decimal number.

We will do this by checking the first value of all substrings, if it is 0 then number is even if 1 then number will be odd. Increment count by length-i as all substrings with this sbstr[0]=’0’ will be even in decimal.

Let us understand with examples.

**Input** − str=”101”

**Output** − Count of even decimal value substrings in a binary string are − 2

**Explanation** − Substrings possible are: 10, 11, 01, 0, 1 out of which 01 is 2 and 0 is 0, 2 are even.

**Input** − str=”111”

**Output** − Count of even decimal value substrings in a binary string are − 0

**Explanation** − Substrings possible are − 11,1 out of which none is even.

We take a string str as 0s and 1’s only.

Store the length of str in len=str.length()

Function count_even(string str, int length) takes the string and its length and returns count of substrings that form an even decimal number.

Traverse string using FOR loop

Starting from index i=0 to i<len, reading binary from left to right.

If any str[i]==’0’ means all substrings starting from it will be even in decimal.

Increment count as length-i.

Return count as result.

#include <bits/stdc++.h> using namespace std; int count_even(string str, int length){ int count = 0; for (int i = 0; i < length; i++){ if (str[i] == '0'){ count += (length - i); } } return count; } int main(){ string str = "00111"; int len = str.length(); cout<<"Count of even decimal value substrings in a binary string are: "<<count_even(str, len) << endl; return 0; }

If we run the above code it will generate the following output −

Count of even decimal value substrings in a binary string are: 9

Advertisements