Leetcode 201 Solution

This article provides solution to leetcode question 201 (bitwise-and-of-numbers-range)

https://leetcode.com/problems/bitwise-and-of-numbers-range

Solution

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int res = 0;

        for (int i = 31; i >= 0; i--)
        {
            int bit1 = (m >> i) & 1;
            int bit2 = (n >> i) & 1;

            if (bit1 == 0 && bit2 == 0)
                continue;
            else if (bit1 == 0 || bit2 == 0)
                break;
            else
                res |= (1 << i);
        }

        return res;
    }
};