Python Program to Clear the Rightmost Set Bit of a Number


When it is required to clear the rightmost bit of a number which was previously set, the ‘&’ operator can be used.

Below is the demonstration of the same −

Example

 Live Demo

def clear_right_bit(my_val):
   return my_val & (my_val-1)
n_val = 6
print("The vlaue of n is :")
print(n_val)
print("The number after unsetting the rightmost set bit is ")
print(clear_right_bit(n_val))

Output

The vlaue of n is :
6
The number after unsetting the rightmost set bit is
4

Explanation

  • A method is defined that takes an integer as a parameter.

  • It computes the ‘&’ operation between the number and the number decremented by 1.

  • Outside the method, an integer is defined, and the method is called by passing the parameter.

  • The output is displayed on the console.

Updated on: 19-Apr-2021

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements