lsb = x & -x isolates the least-significant set bit. Adding lsb to x propagates a carry through the trailing 1-run and clears that run, while setting the bit immediately left of the run. AND-ing the sum with the original x clears that newly set bit and leaves higher bits intact, resulting in the rightmost contiguous 1-run turned off.
If you repeatedly remove the least-significant set bit while it remains adjacent to the rightmost run, you clear the whole contiguous run. This is simple and explicit but costs proportional to the run length.
⏰ Time complexity: O(k), where k is the length of the rightmost contiguous 1-run (number of trailing ones cleared).
🧺 Space complexity: O(1).
Notes
Method 1 is constant-time and preferred. Method 2 is instructive and shows the explicit process; use it if you need to operate per-bit.
The formula relies on two’s-complement arithmetic for -x and is standard in bit manipulation practice. Original reference is preserved in source_links.