# Two Line Solution

• public class Solution {
public int rangeBitwiseAnd(int m, int n) {
while (n - 1 >= m) n &= n - 1;
return n;
}
}

• Good solution, but could you please tell me why the inverse can't work. I get time limit when trying to iterate from m to n.

• @LinHungShi Could you post your answer?

• @hejun_alex

``````public int rangeBitwiseAnd(int m, int n) {
while (m + 1 <= n) m &= m + 1;
return m;
}
}``````

• @LinHungShi So have you found out why the m to n sequence does not work? Thanks

• @John567 When we do m &= m + 1, it only makes m smaller, which means m will never be larger than n. I guess what the algorithm does is that each time we do n &= n - 1, it changes a few right bits to zeros while maintaining the left bits to 1. When n is smaller than m, n and will stop changing even if we do AND with the remains. For example, m = 25, n = 28. When do 28 & 25, the leftmost two bits are one, but the remains are zeros (11000). Since 11000 is smaller than 11001, we don't need to do AND with 26 and 25.

• @LinHungShi Thank you! It make sense!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.