From ab41f0205c93edb38bca8d00506915c4764b1504 Mon Sep 17 00:00:00 2001 From: deerred643-star Date: Sun, 13 Sep 2026 05:15:11 +0800 Subject: [PATCH] Add clear least significant set bit operation --- .../single_bit_manipulation_operations.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/bit_manipulation/single_bit_manipulation_operations.py b/bit_manipulation/single_bit_manipulation_operations.py index fcbf033ccb24..95be4be976d8 100644 --- a/bit_manipulation/single_bit_manipulation_operations.py +++ b/bit_manipulation/single_bit_manipulation_operations.py @@ -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