C++ solution easy understand

  • 0

    1.If m == n, we just return m or n.

    2.If the number of binary bits of m and n are not equal to each other, we return 0. Because if the numbers of binary bits are not equal, suppose m = 0000, 1011, n = 0001, 0000, you will find that once the number of the binary bits are not equal(in this case m contains 4 bits, leading zeros can be ignored, and n contains 5 bits), X = X & Xi, where m <= i <= n, the result of X will be zero.

    3.If the number of binary bits of m and n are equal to each other, then the only thing we should concern about is those bits that m and n are different from to each other(in this case n - m = 5, 5 contains 3 bits), so the lower 3 bits of the result should be set to zeros, and the higher bits of the result should be set to m & n.

    class Solution {
    int rangeBitwiseAnd(int m, int n) 
        if (m == n)
            return m;
    	int mnumOfBinaryBits = binaryBits(m);
    	int nnumOfBinaryBits = binaryBits(n);
    	if (mnumOfBinaryBits != nnumOfBinaryBits)
    		return 0;
        int diffnumOfBinaryBits = binaryBits(n - m);
    	return m & n & (0xffffffff << diffnumOfBinaryBits);
    int binaryBits(int n)
    	int cnt = 0;
    	if (n == 0)
    		return 1;
    	while (n > 0)
    		n /= 2;
    	return cnt;

Log in to reply

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