Divide Two Integers

LeetCode Q 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.

Solution

Basic idea is to utilize subtraction, checking how many times a dividend can substract a divisor. But this approach has a potential to cause time limit exceeds, when the dividend is very large.
So, we increase the divisor at each substraction, say we double the divisor.
At the same time, we need a variable to record how many times is the current divisor of the original divisor.

Note:

  • To deal with the corner case, int need to be converted to long first, then take the absolute value.
  • tempDivisor should not double anymore if we know it will larger than dividend.

Code:

public int divide(int dividend, int divisor) {

  if (dividend == 0)
    return 0;

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

  long dividendLong = Math.abs((long) dividend);
  long divisorLong = Math.abs((long) divisor);

  long res = divideHelper(dividendLong, divisorLong);

  if (res == Integer.MAX_VALUE) 
    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;

  return sign * (int) res;
}

private long divideHelper(long dividend, long divisor) {
  if (dividend < divisor)
    return 0;

  long sum = divisor, multiplication = 1;
  while (sum + sum < divisor) {
    sum += sum; multiplication += multiplication;
  }

  return multiplication + divideHelper(dividend - sum, divisor);
}

   Reprint policy


《Divide Two Integers》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC