给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内全部数字的按位与(包含 m, n 两端点)。python
示例 1:ios
输入: [5,7] 输出: 4
示例 2:c++
输入: [0,1] 输出: 0
因为是按位与,那么某位一旦出现0,结果该位确定是0。因此只须要考虑m,n都是1的位置。那么直接从高位开始,往低位走,直到遇到该为的数字不相等,将其后的数为都置为0,即为[m,n]之间全部的数字按位与的结果。代码以下spa
#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; }