Question: https://leetcode.com/problems/bitwise-and-of-numbers-range/

Question Name: Bitwise AND of Numbers Range

A variant of number of 1 bits in an interger. For any non-zero interger 0b?????????1000 (? could be 1 or 0, and there are zero or one or more 0s after the last 1 bit.), to remove the last 1 bit with bit AND operation, the least to-AND integer, or in other words the next effective integer larger than itself, is 0b????????(?+1)0000. And for any integer i between 0b?????????1000 and 0b????????(?+1)0000, such as 0b?????????1001, 0b?????????1000 & i = 0b?????????1000, no effect at all.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ current = m while current != 0: last_one_bit = current & ((current - 1) ^ current) if current + last_one_bit <= n: current = (current - 1) & current else: break return current |