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.但是不用所有的数字都计算了,只要计算开头结尾就行了。因为他们的最左公共部分是最短的。
因此得到代码:
1 2 3 4 5 6 7 8 9 |
|