您的位置:首页 > 其它

LeetCode:Bitwise AND of Numbers Range

2016-06-11 20:16 267 查看


Bitwise AND of Numbers Range

Total Accepted: 35825 Total
Submissions: 115763 Difficulty: Medium

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.
Credits:

Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Bit Manipulation

思路:

[m,n]中的所有数做“与”运算时,结果中第i位为1的条件是[m,n]中所有第i位都为1,否则为0。

因此,只需要判断m与n的最高位是否同时为1,不同时为1的话,结果为0;

同时为1时,假设这一位是第i位,这时结果为1<<i,即2^i。

java code:

public class Solution {
public int rangeBitwiseAnd(int m, int n) {

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