leetcode 29. divide two integers

29. Divide Two Integers

Difficulty: Medium

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:

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

Example 2:

1
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.

Solution

Language: Java

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class  {
public int divide(int dividend, int divisor) {
if (dividend == 0){
return 0;
}
if (divisor == 1){
return dividend;
}
long divid = (long) dividend;
long divir = (long) divisor;
boolean opposite = false;
if (divid < 0 && divir > 0){
opposite = true;
divid = -divid;
}
if(divid > 0 && divir < 0){
opposite = true;
divir = -divir;
}
if (divid < 0 && divir < 0){
divir = -divir;
divid = -divid;
}
long output = 0;
int shift = 0;
long oldd = divir;
while (divir <= divid){
while (divir <= divid){
divir <<= 1;
shift++;
}
divir >>= 1;
shift--;
divid -= divir;
divir = oldd;
output += ((long)1 << shift);
shift = 0;
}
if (opposite){
output = -output;
}
if (output > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
return (int)output;
}
}