← DiffPush

Set the righmost unset bit

Baseline Bit Manipulation · Learn Bit Manipulation O(1) · O(1)

Lighting the First Vacant Stall

A stable's occupancy board packs stall states into one integer, and the groundskeeper lights the nearest vacant stall — the rightmost 0 bit — whenever a new horse arrives. If every stall already reads 1, the board must stay untouched. Adding one to the board flips the run of trailing full stalls and exposes the vacancy, and an OR with the original lights exactly that spot.

Input: A non-negative integer n.

Output: n with its rightmost unset bit set; n itself when every bit within its width is already set.

Constraints

Examples

Example 1

Input: {"n":6}
Output: 7
110 becomes 111 — the only vacancy is the last stall.

Example 2

Input: {"n":15}
Output: 15
1111 has no vacancy, so the board stays as it is.

Solve this in your browser →

Also on LeetCode ↗