Python Program to Clear the Rightmost Set Bit of a Number

When it is required to clear the rightmost set bit of a number, the bitwise AND (&) operator can be used with a clever mathematical property. This technique involves performing n & (n-1) which effectively removes the rightmost 1 bit from the binary representation.

How It Works

The operation n & (n-1) works because when you subtract 1 from a number, all bits to the right of the rightmost set bit get flipped, including the rightmost set bit itself. The AND operation then clears that bit.

Binary Visualization

Let's see how this works with number 6 ?

# Binary representation
6 in binary:   110
5 (6-1):       101
6 & 5:         100 (which is 4 in decimal)

Example

def clear_right_bit(my_val):
    return my_val & (my_val - 1)

n_val = 6
print("The value of n is:")
print(n_val)
print(f"Binary representation: {bin(n_val)}")
print("The number after unsetting the rightmost set bit is:")
result = clear_right_bit(n_val)
print(result)
print(f"Binary representation: {bin(result)}")
The value of n is:
6
Binary representation: 0b110
The number after unsetting the rightmost set bit is:
4
Binary representation: 0b100

Testing with Different Numbers

def clear_right_bit(my_val):
    return my_val & (my_val - 1)

test_numbers = [12, 8, 7, 15]

for num in test_numbers:
    result = clear_right_bit(num)
    print(f"{num} ({bin(num)}) -> {result} ({bin(result)})")
12 (0b1100) -> 8 (0b1000)
8 (0b1000) -> 0 (0b0)
7 (0b111) -> 6 (0b110)
15 (0b1111) -> 14 (0b1110)

Key Points

  • The method uses bitwise AND operation between the number and the number decremented by 1

  • This technique always clears the rightmost set bit (rightmost 1)

  • If the number is 0, the result remains 0

  • Time complexity is O(1) - constant time operation

Conclusion

The n & (n-1) operation is an elegant bit manipulation technique to clear the rightmost set bit. This method is commonly used in algorithms involving bit counting and optimization problems.

Updated on: 2026-03-25T19:21:06+05:30

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements