您的位置:首页 > 其它

leetcode Bitwise AND of Numbers Range

2015-09-13 18:49 309 查看
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.

这题考的是位操作

需要探索的一个基本式子是 (n & (n - 1))

假设有这样一个数xxxxxxxxxxx10000(这里示意的是最右边一个为1的位,x表示可为1可为0)

那么n - 1 = xxxxxxxxxxx01111

n & (n - 1)呢?

我们发现恰好将最右边那个1消去了.

等等,似乎还有信息可以发掘n = xxxxxxxxxxx10000, n - 1 = xxxxxxxxxxx01111, n & (n - 1) = xxxxxxxxxxx00000

有没有发现 n 和 (n & (n - 1))之间差了可不只1啊, 那这之间的数是个什么形式呢??

n =     xxxxxxxxxxx10000

n - 1 =      xxxxxxxxxxx01111

         xxxxxxxxxxx01110

     ......

     xxxxxxxxxxx0xxxx

     ......

n & (n - 1) = xxxxxxxxxxx00000

有没发现,所有这些数相与的结果就是n & (n - 1)

所以解法就很简洁了:

int rangeBitwiseAnd(int m, int n) {
while(n > m)
n &= n - 1;
return n;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: