50 ms AC recursion solution which need not to convert int inputs to long int data type.


  • 0
    F
    public int Divide(int dividend, int divisor)
            {
                if (dividend == int.MinValue || divisor == int.MinValue)
                {
                    if (dividend == int.MinValue && divisor == int.MinValue)
                    {
                        return 1;
                    }
                    else if (divisor == int.MinValue)
                    {
                        return 0;
                    }
                    else
                    {
                        if (divisor == -1)
                        {
                            return int.MaxValue;
                        }
                        else if (divisor == 2 || divisor == -2)
                        {
                            if (divisor == 2)
                            {
                                return int.MinValue >> 1;
                            }
                            else
                            {
                                return -1 * (int.MinValue >> 1);
                            }
                        }
                        else
                        {
                            int x = Divide(dividend + 1, divisor);
                            int y = Divide(-1, divisor);
                            return x + y;
                        }
                    }
                }
                else
                {
                    int sign = (dividend ^ divisor) >= 0 ? 1 : -1;
                    dividend = Math.Abs(dividend);
                    divisor = Math.Abs(divisor);
                    int originalDivisor = divisor;
                    if (dividend == divisor)
                    {
                        return sign;
                    }
                    else if (dividend < divisor)
                    {
                        return 0;
                    }
                    else
                    {
                        int rst = 1;
                        while ((divisor << 1) > divisor &&
                               (divisor << 1) <= dividend)
                        {
                            rst <<= 1;
                            divisor <<= 1;
                        }
                        return sign * (rst + Divide(dividend - divisor, originalDivisor));
                    }
                }
            }
    

Log in to reply
 

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