mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 13:33:11 +08:00
Add clear least significant set bit operation (#15305)
Co-authored-by: deerred643-star <deerred643-star@users.noreply.github.com>
This commit is contained in:
@@ -94,6 +94,29 @@ def get_bit(number: int, position: int) -> int:
|
||||
return int((number & (1 << position)) != 0)
|
||||
|
||||
|
||||
def clear_least_significant_set_bit(number: int) -> int:
|
||||
"""
|
||||
Clear the least significant set bit (rightmost 1 bit).
|
||||
|
||||
Subtracting 1 changes the rightmost 1 to 0 and the 0 bits to its right to 1.
|
||||
ANDing the result with the original number therefore clears that set bit.
|
||||
For negative integers, Python's infinite sign extension is used.
|
||||
https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
|
||||
|
||||
>>> clear_least_significant_set_bit(0b101100) # 0b101000
|
||||
40
|
||||
>>> clear_least_significant_set_bit(0b1000) # 0b0
|
||||
0
|
||||
>>> clear_least_significant_set_bit(0)
|
||||
0
|
||||
>>> clear_least_significant_set_bit(0b1111) # 0b1110
|
||||
14
|
||||
>>> clear_least_significant_set_bit(-5)
|
||||
-6
|
||||
"""
|
||||
return number & (number - 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
|
||||
Reference in New Issue
Block a user