【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++:

 1 class Solution {

 2 public:

 3     int rangeBitwiseAnd(int m, int n) {

 4         int offset = 0;

 5         while(m!=n){

 6             m>>=1;

 7             n>>=1;

 8             offset++;

 9         }

10         return m<<offset;

11     }

12 };

 

Python:

 1 class Solution:

 2     # @param {integer} m

 3     # @param {integer} n

 4     # @return {integer}

 5     def rangeBitwiseAnd(self, m, n):

 6         offset = 0

 7         

 8         while m != n:

 9             m = m >> 1

10             n = n >> 1

11             offset = offset + 1

12             

13         ret = m << offset

14         

15         return ret

 

你可能感兴趣的:(LeetCode)