Set / Unset the Rightmost Unset Bit
Implement setRightmostUnsetBit
Given a non-negative integer
n, set its rightmost unset (0) bit to 1 and return the result. If every bit within n's current width is already set, the next bit position beyond its highest set bit gets set instead.
Scanning bit by bit until the first 0 is found works, but there's a neat identity: n | (n + 1) always sets exactly that bit. Adding 1 to n flips every trailing run of 1 bits to 0 and carries into the first 0 — a bit that's now set only in n + 1 — so OR-ing the two together restores everything else while keeping that one newly-set bit.
Example 1:
Input: n = 6
Output: 7
Example 2:
Input: n = 15
Output: 31
Example 3:
Input: n = 0
Output: 1
+ 9 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 10⁸
n =
6