My c++ solution 8ms


  • 0
    L
        class Solution {
    public:
        int divide(int dividend, int divisor)
        {
        	if (divisor == 0)
        		return INT_MAX;
        	if (dividend == INT_MIN&&divisor == -1)
        		return INT_MAX;
        	if (divisor == INT_MIN)
        		return dividend == INT_MIN;
    		
    	bool b = (((dividend >> 31) ^ (divisor >> 31))==0);//符号位
    	
    	unsigned int x = dividend>0 ? dividend : -dividend;
    	unsigned int y = divisor>0 ? divisor : -divisor;
    	int res = 0;
    	int a = 1;
    	int m = y;
    	while (x>=m)
    	{
    		if (m >= 1073741824)
    		{
    			res += a;
    			x -= m;
    			a=1;
    			m=y;
    			continue;
    		}
    		else
    		{
    			a = a << 1;
    			m = m << 1;
    		}
    		if (m>=x)
    		{
    			if (m <= x)
    			{
    				res += a;
    				x -= m;
    			}
    			else
    			{
    				res += a>>1;
    				x -= m>>1;
    			}
    			m = y;
    			a = 1;
    		}
    	}
    	return b ? res : -res;
    }
    

    };


Log in to reply
 

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