# Python Program to Clear the Rightmost Set Bit of a Number

This is a Python program to clear the rightmost set bit of a number.

Problem Description

A number is given. We have to clear the rightmost set bit of the number. That is, we have to flip the rightmost 1 in the binary representation of n.

Problem Solution

1. The function clear_rightmost_set_bit is defined.
2. It takes a number n as argument and returns n with its rightmost set bit cleared.
3. This is done by computing n & (n – 1) and returning it.
4. (n – 1) equals n with all the rightmost consecutive 0s and the first rightmost 1 flipped.
5. Thus n & (n – 1) equals n with its rightmost 1 cleared.

Program/Source Code

Here is the source code of a Python program to clear the rightmost set bit of a number. The program output is shown below.

```def clear_rightmost_set_bit(n):
"""Clear rightmost set bit of n and return it."""
return n & (n - 1)

n = int(input('Enter a number: '))
ans = clear_rightmost_set_bit(n)
print('n with its rightmost set bit cleared equals:', ans)```
Program Explanation

1. The user is prompted to enter a number.
2. clear_rightmost_set_bit is called on the number.
3. The return value is displayed.

Runtime Test Cases
```Case 1:
Enter a number: 5
n with its rightmost set bit cleared equals: 4

Case 2:
Enter a number: 0
n with its rightmost set bit cleared equals: 0

Case 3:
Enter a number: 1
n with its rightmost set bit cleared equals: 0```

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]