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.

分析:http://www.cnblogs.com/grandyang/p/4431646.html

我们先从题目中给的例子来分析,[5, 7]里共有三个数字,分别写出它们的二进制为:

101  110  111

相与后的结果为100,仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分,如果上面那个例子不太明显,我们再来看一个范围[26, 30],它们的二进制如下:

11010  11011  11100  11101  11110

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

 

posted @ 2016-08-03 07:19  北叶青藤  阅读(170)  评论(0)    收藏  举报