Leetcode 201. Bitwise range of numbers and problem-solving ideas and implement C ++

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90733575

method one:

Problem-solving ideas:

This question is, in fact, is to find 32-bit binary numbers m and n in front of the common part, then the back filled with zeros. Since in the latter position, there must be a certain number k, m <= k <= n, and the 32-bit binary number k is 0 at that position, then the bitwise done, then it is a 0 to a.

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int tmp = 0;
        while(m != n){
            m = m >> 1;
            n = n >> 1;
            tmp++;
        }
        return m << tmp;
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/90733575