[LeetCode] Divide Two Integers

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, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

Note:

  • Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
private:
long shift(long &dividend, long shiftedDivisor, int shifted) {
if(dividend < shiftedDivisor)
return 0;
long ret = shift(dividend, shiftedDivisor << 1, shifted + 1);
if(dividend >= shiftedDivisor) {
dividend -= shiftedDivisor;
return ret + pow(2, shifted);
}
return ret;
}
public:
int divide(int dividend, int divisor) {
long shiftedDivisor = divisor;
long positiveDividend = dividend;

if(shiftedDivisor < 0) shiftedDivisor *= -1;
if(positiveDividend < 0) positiveDividend *= -1;

if(!divisor)
return INT_MAX;

return min((long)INT_MAX, (divisor < 0 && dividend < 0) || (divisor > 0 && dividend > 0) ? shift(positiveDividend, shiftedDivisor, 0) : -1 * shift(positiveDividend, shiftedDivisor, 0));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/14/PS/LeetCode/divide-two-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.