Skip to main content

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 β†’ 1011
  • n & (n - 1) = 1100 & 1011 = 1000 β†’ Rightmost 1 is 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​

MetricValue
TimeO(1)
SpaceO(1)

⚠️ Edge Cases​

  • n = 0: All bits already unset β†’ returns 0
  • n with only one bit set (e.g. n = 8 β†’ 1000) β†’ becomes 0

πŸ’‘ Other Approaches​

ApproachTimeDescription
Bitmasking via loopO(logN)Loop to find first set bit, clear it
Built-in GCC methodO(1)n &= n - 1 internally used in popcount


πŸ’¬

Discussion & Doubts