题目要求: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) { // 当 dividend = INT_MIN 时, -dividend 会溢出,所以用 long long long long a = dividend >= 0 ? dividend : -(long long)dividend; long long b = divisor >= 0 ? divisor : -(long long)divisor; const bool sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0); // 异号 // 当 dividend = INT_MIN 时, divisor = -1 时,结果会溢出,所以用 long long long long result = 0; while (a >= b) { long long c = b; for (int i = 0; a >= c; ++i, c <<= 1) { a -= c; result += 1 << i; } } if(sign == 0 && result >= 2147483647) result = 2147483647; if(sign == 1 && result <= -2147483647) result = -2147483647; return ((dividend^divisor) >> 31) ? (-result) : (result); } };