Maybe my idea is a little bit complex. But I still think that's not bad


  • 0
    H

    go through m, check every bit is 1;
    m+tag will be the smallest number for (m+tag)&m get 0 in that bit,
    and pay attention we need to set all the bit we have searched as 0, only after this, the answer of m + tag will be the number we want

    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            if (n-m ==1 || m == n)return m&n;
            int res = 0;
            int tag = 1;
            while (m >= tag) {
                if ((m & tag) > 0) {
                    if (m+tag > n){
                        res += tag;
                    }
                }
                 m &= ~tag;
                tag <<= 1;
            }
            return res;
        }
    }
    

Log in to reply
 

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