
lo
(图片来源https://leetcode.com/problems/bitwise-and-of-numbers-range/
)
| 日期 | 是否一次通过 | comment |
|---|---|---|
| 2020-01-11 |
留意下:
- longest common prefix of all integer
public int rangeBitwiseAnd(int m, int n) {
int i = 0; // i means we have how many bits are 0 on the right
while(m != n){
m >>= 1;
n >>= 1;
i++;
}
return m << i;
}
public int rangeBitwiseAnd1(int m, int n) {
if (m == n){
return m;
}
//The highest bit of 1 in diff is the highest changed bit. 得到不同的后几位
int diff = m ^ n;
//Index is the index of the highest changed bit. Starting at 1. 10进制转2进制位数
int index = (int)(Math.log(diff) / Math.log(2)) + 1;
//Eliminate the changed part.
m = m >> index;
return m << index;
}