[leetcode] Bitwise AND of Numbers Range

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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Have you met this question in a real interview?
 
思路:
找规律即可,通过分析我们发现:
1,当 m = n时,直接返回m或者n即可。
2,当表示m和n的二进制的数的长度不相等时,由于低一位像高一位进位时,出现的数必然为100...0,长度比低位的数长了一位,此数与长度比它小的数“与”,结果必然为0,0“与”任何数都为0。即,当表示m,n的二进制数的长度不一致时,从m到n进行“与”操作,结果为0;
3,当二者长度一致时,进行循环与操作即可。只是要注意:n为INT_MAX 时,需要特殊处理。
 
class Solution
{
public:
  int rangeBitwiseAnd(int m, int n)
  {
    int ret = m;
    int a = m, b = n;
    int lena = 1, lenb = 1;

    if(m == n)
      return m;

    while(a >>= 1)
      lena++;

    while(b >>= 1)
      lenb++;

    if(lena == lenb)
    {
      for(int i = m + 1; i <= n; i++)
      {
        ret &= i;
        if(i == INT_MAX)
          break;
      }
    }
    else
      ret = 0;
     
    return ret; 
  }
};
原文地址:https://www.cnblogs.com/lxd2502/p/4479970.html