Share my 61ms solution with c++


  • 0
    C
    class Solution {
    public:
        int rangeBitwiseAnd(int m, int n) {
            if (m == 0)
                return 0;
            int tmp = m, h = 1, bits = 0, rslt = 0;
            while (tmp) {
                tmp >>= 1;
                h <<= 1;
                bits ++;
            }
            if (bits < 31 && n >= h) {
                return 0;
            }
            bits --;
            int t = 1 << bits;
            while (t) {
                while ((m & t)) {
                    rslt |= t;
                    t >>= 1;
                }
                while (t && !(m & t)) {
                    if (n & t) {
                        return rslt;
                    }
                    t >>= 1;
                }
            }
            return rslt;
        }
    };

Log in to reply
 

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