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;
}

原文地址:https://www.cnblogs.com/crackpotisback/p/10203113.html