1. 程式人生 > >leetcode 201. 數字範圍按位與 解題報告

leetcode 201. 數字範圍按位與 解題報告

給定範圍 [m, n],其中 0 <= m <= n <= 2147483647,返回此範圍內所有數字的按位與(包含 m, n 兩端點)。

示例 1:

輸入: [5,7]
輸出: 4

示例 2:

輸入: [0,1]
輸出: 0

思路分析

由於是按位與,那麼某位一旦出現0,結果該位肯定是0。所以只需要考慮m,n都是1的位置。那麼直接從高位開始,往低位走,直到遇到該為的數字不相等,將其後的數為都置為0,即為[m,n]之間所有的數字按位與的結果。程式碼如下

#include<bits/stdc++.h>

using namespace std;
static auto x = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    return 0;
}();

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int ret = 0;
        for(int i = 31; i >= 0; --i){
            int c = (1<<i);
            if((m&c) == (n&c)){
                ret |= (m&c);
            }else break;
        }
        return ret;
    }
};

int main() {

    return 0;
}