Skip to content

201. Bitwise AND of Numbers Range

Jacky Zhang edited this page Sep 2, 2016 · 1 revision

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.

这道题的技巧是:

  1. 若m != n,则最后一位必然是0;
  2. 每次将m,n右移一位直到m == n,并设一个factor来记录iteration次数。
public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        if(m == 0) return 0;
        int moveFactor = 1;
        while(m != n) {
            m >>= 1;
            n >>= 1;
            moveFactor <<= 1;
        }
        return m * moveFactor;
    }
}
Clone this wiki locally