LeetCode – Bitwise AND of Numbers Range (Java)

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Java Solution

The key to solve this problem is bitwise AND consecutive numbers. You can use the following example to walk through the code.

    8  4  2  1
---------------
5 | 0  1  0  1
6 | 0  1  1  0
7 | 0  1  1  1
public int rangeBitwiseAnd(int m, int n) {
     while (n > m) {
          n = n & n - 1;
     }
     return m & n;
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Darewreck
  • Yun Qin

    The problem is all about finding the longest common sequence between n and m starting from the most significant bit, since all the following bits will flip for at least once and the AND result will be 0.
    To find the longest common sequence, we remove one trailing 1 from n each time and see if it’s still greater than m, otherwise n will be the longest sequence.
    What I don’t understand is why we can’t simply return n in the last step?

  • Akhil

    can someone explain the proof of this algorithm!!