Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
给定范围[m, n],其中 0 <= m <= n <= 2147483647,返回范围内所有整数的按位与,包括边界。
例如,给定范围[5, 7], 你应该返回4。
bin dec 101 5 110 6 111 7 ------------- 100 4
解题思路:
由数据范围 0 <= m <= n <= 2147483647可知,时间复杂度O(n)及以上的解法是不可接受的。
因此可以判断此题为数学题。
参考LeetCode Discuss链接:https://leetcode.com/discuss/32053/accepted-c-solution-with-simple-explanation
[m, n]范围的按位与的结果为m与n的公共“左边首部(left header)”
class Solution(object):
def rangeBitwiseAnd(self, m, n):
res = 0
while m != n:
res += 1
m = m >> 1
n = n >> 1
res = m << res
return res