範圍數位與結果

原題

  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.算法

題目大意

   給一個範圍,返回這個範圍中全部的數按位相與最後的結果。this

解題思路

  當m!=n,那麼最末位一定等0,由於[m, n]一定包含奇偶數,相與最末位等0。能夠將m,n都右移一位,記爲mk、 nk,這樣就至關於將[m, n]之間的全部的數都右移動了一位,當mk=nk的時候,說明以前[m, n]之間的數右移一位後是相等的,右移後的數做AND操做,結果仍是m(=n),因此操做就能夠中止了記錄右移的次數,offset,m>>offset即爲所求結果spa

代碼實現

算法實現類.net

public class Solution {

    public int rangeBitwiseAnd(int m, int n) {
        int offset = 0;

        while (m != n) {
            m >>= 1;
            n >>= 1;
            offset++;
        }

        return m << offset;
    }
}
相關文章
相關標籤/搜索