LeetCode 201. Bitwise AND of Numbers Range

可通过的代码:

class Solution 
{
public:
    int rangeBitwiseAnd(int m, int n) 
    {
        int ret = 0;
        for (int i = 0; m!=0 && n!=0 && i<31; n>>=1, m>>=1, i++)
        {
        	ret += ((m%2!=0)&&m==n? (1<<i): 0);
        }
        return ret;
    }
};

在VS2013下测试成功(n=1, m=1, 输出1),提交到网上测试失败(n=1, m=1, 提示输出0)的代码:

class Solution 
{
public:
    int rangeBitwiseAnd(int m, int n) 
    {
		int ret = 0;
		for (int i = 0; i < 31; ++ i)
		{
			ret |= (((n-m)>(1<<(i+1)) || (n/(1<<i))%2==0 || (m/(1<<i))%2==0)? 0: (1<<i));
		}  
		return 0;     
    }
};


你可能感兴趣的:(LeetCode,C++)