29 Divide Two Integers

Last Updated on: January 6, 2021 pm

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

Example 1:

1
2
3
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.

Example 2:

1
2
3
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -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.

Code

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
class Solution {
public int divide(int dividend, int divisor) {
if(dividend == 0)
return 0;
if(dividend == Integer.MIN_VALUE && divisor == -1)
return Integer.MAX_VALUE;

if(divisor == 1)
return dividend;
int sign = 1;
if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))
sign = -1;

long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
int res = 0;
while(a >= b){
int shift = 0;
while(a >= (b<<shift)){
shift++;
}
a -= b<<(shift - 1);
res += 1 << (shift - 1);
}
return sign * res;
}
}