您的位置:首页 > 其它

Leetcode: Bitwise AND of Numbers Range

2015-12-15 02:14 417 查看
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.


Analysis: O(N) solution will cause TLE, so this is a math problem and should generate O(1) solution

First trial: slow.

Check all 32 bits. see if both m(lower bound) and n(higher bound) are 1 on ith bit. Also need to check if diff=n-m+1 is greater than 2^i, which is the max range that 1 is fixed on this bit.

public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int res = 0;
int diff = n-m+1;
int maxRange = 1;
for (int i=0; i<=31; i++) {
maxRange = (int)Math.pow(2, i);
if (diff > maxRange) continue;
int mi = (m>>i) & 1;
int ni = (n>>i) & 1;
if (mi == 1 && ni == 1) res |= 1<<i;
}
return res;
}
}


Better solution: this is actually finding the Shared Header(公共头部)

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