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.
思路:
先找前面二进制相同的位,后面不相同的位相与一定为0.
比如: 1111001
1110011
从0011 - 1001 中间一定会经过 1000 从而使这四位都为0
我的代码:
int rangeBitwiseAnd(int m, int n) { int ans = 0; int t = 30; while(t >= 0 && ((m & (1 << t)) == (n & (1 << t)))) { ans |= m & (1 << t); t--; } return ans; }
别人的代码:更精简
int rangeBitwiseAnd(int m, int n) { int r=Integer.MAX_VALUE; while((m&r)!=(n&r)) r=r<<1; return n&r; }