easy +8 pts

Clear Rightmost Set Bit

Implement a function that clears the lowest set bit of a non-negative integer using bitwise operations.

Write a function `clear_rightmost_set_bit(n)` that takes a non-negative integer `n` and returns the result of clearing the rightmost (least significant) set bit in its binary representation. The rightmost set bit is the lowest-order bit that is 1. The returned value should be the integer formed after changing that bit from 1 to 0, while leaving all other bits unchanged. For example, the binary representation of 12 is `1100`. The rightmost set bit is at position 2 (0-indexed from the left? Actually, from the right, the first 1 from the least significant bit). Clearing it gives `1000`, which is 8. You must implement the function using bitwise operations (e.g., `&`, `|`, `~`, `-`, `^`, shifts). Do not use loops or string manipulation. The solution should be O(1) time. **Input:** Non-negative integer `n` (0 ≤ n ≤ 10^9).

Constraints

0 ≤ n ≤ 10^9 - Must use bitwise operations only (no loops, no string conversion, no division/multiplication by 2 except via shifts if needed). - Expected time complexity: O(1).

Example

>>> clear_rightmost_set_bit(12)
8
>>> clear_rightmost_set_bit(7)
6
>>> clear_rightmost_set_bit(0)
0
>>> clear_rightmost_set_bit(16)
0
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider the bitwise AND of n and n-1.
n & (n-1) clears the lowest set bit.
Test with n=0 (returns 0), n=1 (returns 0 if n>0).
Remember that for n=0, the formula n & (n-1) gives 0 & (-1) = 0, which is correct.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.