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.

分析:第一种都容易想到,将所有数字进行AND操作,肯定超时的啦

复制代码
1 class Solution {
2 public:
3     int rangeBitwiseAnd(int m, int n) {
4         int result = 1;
5         for(int i = m; i <= n; i++) result = result & i;
6         return result;
7     }
8 };
View Code
复制代码

由于是连续整数进行AND,那么只要有一个位上的数字为0,那么该位的结果就为0. 

如果n位数>m位数,一定会出现100…0的情况,AND的结果为100…00

如果n位数=m位数,从最高位开始分析,如果n和m该位上的数字相等,考虑下一位,直到某位上n=1,m=0(因为n>m)。到这种情况时,一定又会出现100…0的情况,所以后面的这些数字进行AND操作所得结果为0.

所以,不断将m和n进行右移位操作,并用计数器计数,直到m=n。

运行时间229ms。想想该怎么优化吧。。

复制代码
 1 class Solution {
 2 public:
 3     int rangeBitwiseAnd(int m, int n) {
 4         int times = 0;
 5         while(m != n){
 6             m = m >> 1;
 7             n = n >> 1;
 8             times++;
 9         }
10         return m<<times;
11     }
12 };
复制代码

 

posted @   amazingzoe  阅读(110)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示