首页 > 其他 > 详细

Bitwise AND of Numbers Range

时间:2015-05-09 17:28:47      阅读:97      评论:0      收藏:0      [点我收藏+]

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 };

 

Bitwise AND of Numbers Range

原文:http://www.cnblogs.com/amazingzoe/p/4489862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!