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



@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.
