Counting even decimal value substrings in a binary string in C++

C++Server Side ProgrammingProgramming

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.

Approach used in the below program is as follows

  • 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.

Example

 Live Demo

#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;
}

Output

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

Count of even decimal value substrings in a binary string are: 9
raja
Published on 31-Aug-2020 12:06:44
Advertisements