201. Bitwise AND of Numbers Range【M】【80】【leetcode】
来源:互联网 发布:java反射的应用 编辑:程序博客网 时间:2024/06/05 19:17
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.
Subscribe to see which companies asked this question
刚开始理解错了与……写了半天都不对,后来发现没有那么麻烦
给定范围[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
0 0