Bitwise AND of Numbers Range
实现范围内的按位与
思路:首先将m与n做按位与得到tmp。对于tmp中为0的位,则最终结果也一定为0;对于tmp中为1的位,则要看m到n中间有没有数的这一位为0,方法是:将m的这一位及其低位全部置1得到数a,如果a<n,则说明m到n中间存在这一位为0的数。
1 public class Solution { 2 public int rangeBitwiseAnd(int m, int n) { 3 int res = m & n; 4 5 for (int j = 0; j < 31; j++) { 6 if ((res & (1 << j)) != 0) { //如果第j位为0 7 int a = 1 << (j + 1); 8 a--; 9 if ((a | m) < n) { 10 res &= (~(1 << j)); 11 } 12 } 13 } 14 return res; 15 } 16 }