C# accepted, easy to understand, recursive.


  • 3
    R

    This answer is from @applewolf 's one line solution:
    https://leetcode.com/discuss/34918/one-line-c-solution

    if number m < n, then at the last bit, there must exist both 1 and 0, so the AND result at the last bit would be 0.

    For example,
    4: 0100
    AND
    5: 0101

    So the problem became:
    4 >> 1: 0010
    AND
    5 >> 1: 0010

    Then back 1 bit
    0010 << 1 = 0100

    public static int RangeBitwiseAnd(int m, int n)
    {
        if (m < n)
        {
            return (RangeBitwiseAnd(m >> 1, n >> 1) << 1);
        }
        else
        {
            // m = n
            return m;
        }
    }

Log in to reply
 

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