This is a Python program to clear the rightmost set bit of a number.
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.
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.
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)
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.
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.