Add clear_least_significant_set_bit operation - #15305
Conversation
|
ON HOLD: Our focus is on merging or closing old pull requests before October 1st. |
priya-sundaram-dev
left a comment
There was a problem hiding this comment.
LGTM. Clean, well-scoped addition — the n & (n - 1) trick to clear the least significant set bit is exactly right, and I like that the docstring explains why it works rather than just asserting it.
I verified it independently: ran the doctests (21/21 pass) and cross-checked n & (n-1) against n - (n & -n) (subtracting the lowest set-bit value) for positives, negatives, zero, and powers of two (0, 8, 15, 44, 255, 256, -5, -1, -256) — all match, including the two's-complement negative cases your -5 -> -6 doctest covers.
Type hints and doctests are present per the contributing guide. One tiny, non-blocking nit: the linked reference is the Kernighan bit-counting kernel; it uses the same n & (n-1) identity so it's relevant, but a reader might expect a page specifically about clearing the low bit. Fine to leave as-is.
Approving.
Describe your change
This PR adds
clear_least_significant_set_bit(), which usesnumber & (number - 1)to clear the rightmost set bit. The docstring explainsthe bitwise operation and includes doctests for zero, powers of two, multiple
set bits, and negative integers under Python's sign-extension semantics.
Tests
python -m doctest -v bit_manipulation/single_bit_manipulation_operations.pyruff check bit_manipulation/single_bit_manipulation_operations.pyruff format --check bit_manipulation/single_bit_manipulation_operations.pyChecklist
Fixes #12970