Leetcode.js: Divide Two Integers

Apr 17, 2018, 1 min read

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

Return the quotient after dividing dividend by divisor.

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,2311][-2^{31}, 2^{31 -1}]. For the purpose of this problem, assume that your function returns 23112^{31} - 1 when the division result overflows.

Solution:

/**
 * @param {number} dividend
 * @param {number} divisor
 * @return {number}
 */
var divide = function(dividend, divisor) {
  const MAX_INT = ~(1 << 31);
  const MIN_INT = 1 << 31;

  const tmp = dividend / divisor;
  const ans = tmp > 0 ? Math.floor(tmp) : Math.ceil(tmp);

  return Math.min(Math.max(MIN_INT, ans), MAX_INT)
};

Category leetcode.js

Tags leetcode, js

Comments