Unset the Right Most Set Bit
Problem Statement:β
- Example:
β Solution: Bit Manipulationβ
πΉ Operation: Unset the Rightmost Set Bitβ
class Solution {
public:
int unsetRightMostSetBit(int n) {
// Unset the rightmost set bit using n & (n - 1)
return n & (n - 1);
}
};
π How It Worksβ
- The goal is to turn off (unset) the rightmost 1 in the binary representation of a number
n. - The expression
n & (n - 1)does exactly that.
Example:β
Letβs say n = 12 β 1100 in binary.
n - 1 = 11β1011n & (n - 1) = 1100 & 1011 = 1000β Rightmost1is removed β
Why it works?β
- Subtracting 1 flips all bits after the rightmost 1, including the 1 itself.
- Doing AND with original number clears the rightmost
1.
π§© Key Formula / Recurrenceβ
n & (n - 1)
This removes the rightmost set bit.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(1) |
| Space | O(1) |
β οΈ Edge Casesβ
n = 0: All bits already unset β returns 0nwith only one bit set (e.g.n = 8β1000) β becomes0
π‘ Other Approachesβ
| Approach | Time | Description |
|---|---|---|
| Bitmasking via loop | O(logN) | Loop to find first set bit, clear it |
| Built-in GCC method | O(1) | n &= n - 1 internally used in popcount |
π Related Problemsβ
- Count Set Bits β Use this trick repeatedly until
n = 0 - Set the rightmost 0 bit:
n | (n + 1) - Get position of rightmost set bit:
n & -n - Leetcode 191. Number of 1 Bits
- GFG: Check whether all bits are set
π¬