Bit wise And of number range !! 3 line simple solution .


  • 0
    R
    int rangeBitwiseAnd(int m, int n) {
        while(n > m){
            n = n & n-1 ;
        }
        return m&n;
    }

  • 0
    H

    You're doing too many & operations which can be time consuming. You can iteratively reduce the range [m,n] be noting that if m-n>=2, then there must be an even number in the range and you can shift both m,n right by 1 bit. At the end you only have to do 1 & operation. Be sure to shift the result left by the number of times you reduce the range.


  • 0

    @hengliu Since when are & operations slow? And how many & operations do you think this is doing?


Log in to reply
 

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