https://leetcode.com/problems/bitwise-and-of-numbers-range/description/
嗯。这一题,看上去好麻烦啊。但实际上就一点:In one word, this problem is asking us to find the common prefix of m and n 's binary code.
上面那句话照抄了某个dicuss board的一个评论。
所以基于此,做法有很多了。总的来说,我的做法就是找到较大数字的最高位在哪,然后一位位往下进行与操作直到m和n在某一位不等就停。
public int logn(int m, int n) {
return (int)(Math.log((double)m) / Math.log((double)n));
}
public int rangeBitwiseAnd(int m, int n) {
int log2n = logn(n, 2);
int result = 0;
int mbit = 0, nbit = 0;
while (log2n >= 0 && mbit == nbit) {
mbit = (1 << log2n) & m;
nbit = (1 << log2n) & n;
result |= (mbit & nbit);
log2n--;
}
return result;
}