building bit by bit


  • 0
    V

    A lengthy but with a different perspective: 0 th bit has 1 same value, 1 st bit has 2 same values, 2nd has 4 same values, 3rd: 8 and so on.

    public class Solution 
    {
        public int rangeBitwiseAnd(int m, int n) 
        {
            int res = 0;
            if(m == n)
                return m;
            int k = n;
            for(int i = 0; k > 0; i++, k = k >> 1)
            {
                if((m & (1 << i)) > 1)
                {
                    int val = (int)Math.pow(2, i);
                    int t  = 1;
                    t = t << i;
                    t--;
                    if((n - m + 1) <= (val - (m & t)))
                        res |= (1 << i);
                }
            }
            return res;
        }
    }

Log in to reply
 

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