leetcode ——29——Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.


class Solution {
public:
     int divide(int dividend, int divisor)
    {
        int sign = (dividend < 0) ^ (divisor < 0) ? - 1 : 1;
         long long res = 0, m = abs((long long)dividend), n = abs((long long)divisor);
         while(m >= n)
         {
             long long t = n, i = 1;
             while(t << 1 < m)
             {
                 t <<= 1;
                 i <<= 1;
             }
             m -= t;
             res += i;
         }
         if(sign < 0)
             res = -res;
         return res > INT_MAX ? INT_MAX : res;
    }

};

你可能感兴趣的:(LeetCode,算法题)