Bitwise AND of Numbers Range

Leetcode

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.

Analysis

5: 1 0 1
6: 1 1 0
7: 1 1 1
$: 1 0 0

AND 以后输出左边开始共同的部分。所以这道题是找m和n左边的共同部分输出。 step记录总共移了多少次。m和n每次向右移动一位,直到m和n相等。

Code

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int step = 0;
        while(m != n){
            m >>= 1;
            n >>= 1;
            step++;
        }
        return m << step;
    }
}

Reference

Ref1 Ref2