# [LeetCode] 29. Divide Two Integers 两数相除

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

• Both dividend and divisor will be 32-bit signed integers.
• The divisor will never be 0.
• Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

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

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

Github 同步地址：

https://github.com/grandyang/leetcode/issues/29

https://leetcode.com/problems/divide-two-integers/

https://leetcode.com/problems/divide-two-integers/discuss/13524/summary-of-3-c-solutions

https://leetcode.com/problems/divide-two-integers/discuss/13407/C%2B%2B-bit-manipulations

https://leetcode.com/problems/divide-two-integers/discuss/142849/C%2B%2BJavaPython-Should-Not-Use-%22long%22-Int

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2015-04-16 14:04  Grandyang  阅读(29459)  评论(23编辑  收藏  举报