Python Program to Clear the Rightmost Set Bit of a Number

PythonServer Side ProgrammingProgramming

<p>When it is required to clear the rightmost bit of a number which was previously set, the &lsquo;&amp;&rsquo; operator can be used.</p><p>Below is the demonstration of the same &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/ZgqzPGwA" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">def clear_right_bit(my_val): &nbsp; &nbsp;return my_val &amp; (my_val-1) n_val = 6 print(&quot;The vlaue of n is :&quot;) print(n_val) print(&quot;The number after unsetting the rightmost set bit is &quot;) print(clear_right_bit(n_val))</pre><h2>Output</h2><pre class="result notranslate">The vlaue of n is : 6 The number after unsetting the rightmost set bit is 4</pre><h2>Explanation</h2><ul class="list"><li><p>A method is defined that takes an integer as a parameter.</p></li><li><p>It computes the &lsquo;&amp;&rsquo; operation between the number and the number decremented by 1.</p></li><li><p>Outside the method, an integer is defined, and the method is called by passing the parameter.</p></li><li><p>The output is displayed on the console.</p></li></ul>
raja
Updated on 19-Apr-2021 10:48:49

Advertisements