您的位置:首页 > 其它

【leetcode】Bitwise AND of Numbers Range(middle)

2015-04-16 22:34 483 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: