[Leetcode]201. Bitwise AND of Numbers Range @python
来源:互联网 发布:ipad 电容笔 知乎 编辑:程序博客网 时间:2024/05/24 01:32
题目
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.
题目要求
给定m和n要求m到n的所有数字相与的结果。
解题思路
此题参考了书影博客的解题思路。
如果直接计算m到n的所有数相与,复杂度为
代码
class Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ p = 0 while m != n: m >>= 1 n >>= 1 p += 1 return m << p
0 0