201. Bitwise AND of Numbers Range

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.

思路:從左到右比較m和n的二進制數,相同的base加起來,直到出現不同的base,停止比較,因爲後面一定是0,1交錯的,而前面的一定是相同的(比較過來的),只要返回這些相同部分。

public class Solution {
    // //timeout solution
    // public int rangeBitwiseAnd(int m, int n) {
    //     if(m>n) return 0;
    //     int result = m;
    //     for(int i=m+1; i<=n; i++){
    //         result = result & i;
    //     }
    //     return result;
    // }
    public int rangeBitwiseAnd(int m, int n) {
        if(m==0||m==n) return m;
        int copyn = n;
        int result=0,c=0;
        //c is the count of right move of n to make 0
        while(copyn>0){
            copyn>>=1;
            c++;
        }
        while(c>0){
            c--;
            if( (m & (1<<c)) != (n & (1<<c)) ) break;
            result += m & (1<<c);
        }
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章