LeetCode 201 Bitwise AND of Numbers Range

来源:互联网 发布:免费视频编辑软件排行 编辑:程序博客网 时间:2024/06/04 08:30

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.

这个题开始想了想,以为直接loop就行了,但是又一想好歹是个中等难度,有这么简单?管他呢就简单loop。果然==Time Limit Exceeded。那有什么骚操作呢?就参考了别人的解法。有这么一个思路。说结果取决于所有数字的最左公共部分。举例:

4:0100

5:0101

6:0110

7:0111

结果是0100,也就是4.但是不用所有的数字都计算了,只要计算开头结尾就行了。因为他们的最左公共部分是最短的。

因此得到代码:

 

 

123456789
public int rangeBitwiseAnd(int m, int n) {int i = 0;while (m != n) {m >>= 1;n >>= 1;i++;}return m < < i;}
原创粉丝点击