C 49 ms minimal code?


  • 0
    O

    Just trying to reduce down to minimal code (character count), wondering if anyone can do much better

    int rangeBitwiseAnd(int m, int n) {
        int i=-1;
        while(n-m>>++i);
        return n&m>>i<<i;
    }

  • 0
    X

    Good solution! I am just wonder how you test the running time of your solution? under which enviroment? Thanks!


  • 0
    O

    Just going by what leetcode oj clocked it at. This seems to be quite variable...


  • 0
    H

    could you share concept of your solution??


  • 0
    O

    Find the largest bit which isn't equal in both n and m (done here by looking at n-m, counted using 'i' variable). This bit, and all later ones, must be zero.
    Take only bits which are 1 in both n and m, and not in the last i bits (done by right shifting then left shifting). This is the answer


Log in to reply
 

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