# My simple java solution(3 lines)

• The idea is to use a mask to find the leftmost common digits of m and n.
Example: m=1110001, n=1110111, and you just need to find 1110000 and it will be the answer.

``````public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int r=Integer.MAX_VALUE;
while((m&r)!=(n&r))  r=r<<1;
return n&r;
}
``````

}

The approach is to find the leftmost common digits of m and n, but not "leftmost common digits of all 1's for m and n", E.g. m=1110111, n=1110101 and answer is 1110100 but not 1110000.

• Yes, you are right, thanks!

• no worries:)

• your case is not right.
they said 0 <= m <= n <= 2147483647, your case is not right "E.g. m=1110111, n=1110101"

• Can you please explain why the right most common bits of the two numbers will give the answer?

• My Java solution without confusing AND's with Integer.MAX_VALUE.

``````public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int count=0;
while(m!=n) {
m=m>>>1; //shift numbers right
n=n>>>1; //shift numbers right
count=count+1; //keep track of Shifts
}