A solution according to difference between m and n(C++)

  • 1

    int rangeBitwiseAnd(int m, int n) {
    int dif = n-m;
    int tmp = INT_MAX;
    dif >>= 1;
    tmp <<= 1;
    return m&n&tmp;
    As numbers in[m,n],assume dif = n-m,then we can get x bits changed from m to n, which means the lower x bits of the result is 0. After that, using m&n deal with the rest high bits.
    For example,m=0x1010 and n=0x1111, dif = 5, so the lower 3 bits change and the result must be ?000. m&n get 0x1010,so ? is 1.
    Idea is similar and It's just a different expression.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.