leetcode 201. Numerical ranges bitwise AND (& calculation)

Given the range of [m, n], where 0 <= m <= n <= 2147483647, returns all numbers in this range with a bitwise (containing m, n both inclusive).

Example 1: 

Input: [5,7]
Output: 4
Example 2:

Input: [0,1]
Output: 0
Source: stay button (LeetCode)

Link: https: //leetcode-cn.com/problems/bitwise-and-of-numbers-range

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int num=0;
        int k=1<<30;
        while(k>0&&(m&k)==(n&k)){
            num|=k&m;
            k>>=1;
        }
        return num;
    }
};

 

Guess you like

Origin www.cnblogs.com/wz-archer/p/12590233.html