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

C++Server Side ProgrammingProgramming

<p style="">We are given with a string of 0&rsquo;s and 1&rsquo;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.</p><p>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]=&rsquo;0&rsquo; will be even in decimal.</p><p>Let us understand with examples.</p><p><strong>Input</strong> &minus; str=&rdquo;101&rdquo;</p><p><strong>Output</strong> &minus; Count of even decimal value substrings in a binary string are &minus; 2</p><p><strong>Explanation</strong> &minus; Substrings possible are: 10, 11, 01, 0, 1 out of which 01 is 2 and 0 is 0, 2 are even.</p><p><strong>Input</strong> &minus; str=&rdquo;111&rdquo;</p><p><strong>Output</strong> &minus; Count of even decimal value substrings in a binary string are &minus; 0</p><p><strong>Explanation</strong> &minus; Substrings possible are &minus; 11,1 out of which none is even.</p><h2>Approach used in the below program is as follows</h2><ul class="list"><li><p>We take a string str as 0s and 1&rsquo;s only.</p></li><li><p>Store the length of str in len=str.length()</p></li><li><p>Function count_even(string str, int length) takes the string and its length and returns count of substrings that form an even decimal number.</p></li><li><p>Traverse string using FOR loop</p></li><li><p>Starting from index i=0 to i&lt;len, reading binary from left to right.</p></li><li><p>If any str[i]==&rsquo;0&rsquo; means all substrings starting from it will be even in decimal.</p></li><li><p>Increment count as length-i.</p></li><li><p>Return count as result.</p></li></ul><h2>Example</h2><p><a class="demo" href="http://tpcg.io/3tklIBc0" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include &lt;bits/stdc++.h&gt; using namespace std; int count_even(string str, int length){ &nbsp; &nbsp;int count = 0; &nbsp; &nbsp;for (int i = 0; i &lt; length; i++){ &nbsp; &nbsp; &nbsp; if (str[i] == &#39;0&#39;){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;count += (length - i); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return count; } int main(){ &nbsp; &nbsp;string str = &quot;00111&quot;; &nbsp; &nbsp;int len = str.length(); &nbsp; &nbsp;cout&lt;&lt;&quot;Count of even decimal value substrings in a binary string are: &quot;&lt;&lt;count_even(str, len) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>If we run the above code it will generate the following output &minus;</p><pre class="result notranslate">Count of even decimal value substrings in a binary string are: 9</pre>
raja
Updated on 31-Aug-2020 08:37:31

Advertisements