【LeetCode 201】Bitwise AND of Numbers Range

时间:2023-03-09 07:41:13
【LeetCode 201】Bitwise AND of Numbers Range

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] 范围内个数,返回范围内所有数相与的结果。

思路:

  如果打着暴力的旗号,那么这个题是会超时的 - -!。最后也是没脾气了,看了别人的blog,代码很呆萌,原理也很朴实:当m != n时,最末位必定等于0,因为[m,n]必定包含奇偶数,相与最末位等0,这时m和n同时右移一位(offset++);直到当m = n的时候,此时想与已经不会改变什么了,此时的m或者n左移offset位即为结果(好像似乎可能明白了什么,但是好像又什么也没明白 - -!当定理背过如何?)。

C++:

 class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int offset = ;
while(m!=n){
m>>=;
n>>=;
offset++;
}
return m<<offset;
}
};

Python:

 class Solution:
# @param {integer} m
# @param {integer} n
# @return {integer}
def rangeBitwiseAnd(self, m, n):
offset = 0 while m != n:
m = m >> 1
n = n >> 1
offset = offset + 1 ret = m << offset return ret