Skip to content

Commit ab37831

Browse files
Add clear least significant set bit operation (#15305)
Co-authored-by: deerred643-star <deerred643-star@users.noreply.github.com>
1 parent bde9150 commit ab37831

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

bit_manipulation/single_bit_manipulation_operations.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,29 @@ def get_bit(number: int, position: int) -> int:
9494
return int((number & (1 << position)) != 0)
9595

9696

97+
def clear_least_significant_set_bit(number: int) -> int:
98+
"""
99+
Clear the least significant set bit (rightmost 1 bit).
100+
101+
Subtracting 1 changes the rightmost 1 to 0 and the 0 bits to its right to 1.
102+
ANDing the result with the original number therefore clears that set bit.
103+
For negative integers, Python's infinite sign extension is used.
104+
https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
105+
106+
>>> clear_least_significant_set_bit(0b101100) # 0b101000
107+
40
108+
>>> clear_least_significant_set_bit(0b1000) # 0b0
109+
0
110+
>>> clear_least_significant_set_bit(0)
111+
0
112+
>>> clear_least_significant_set_bit(0b1111) # 0b1110
113+
14
114+
>>> clear_least_significant_set_bit(-5)
115+
-6
116+
"""
117+
return number & (number - 1)
118+
119+
97120
if __name__ == "__main__":
98121
import doctest
99122

0 commit comments

Comments
 (0)