/29. Divide Two Integers

29. Divide Two Integers

Medium
Probability19.5% acceptance

Given two signed 32-bit integers, numerator and denominator, compute the integer quotient of numerator divided by denominator without using multiplication, division, or modulo operators. The result must be truncated toward zero. If the quotient exceeds the 32-bit signed integer range [−2^31, 2^31−1], return the closest boundary value. Denominator will never be zero.

Example 1

Input: numerator = 15, denominator = 4

Output: 3

Explanation: 15 / 4 = 3.75, truncated toward zero is 3.

Example 2

Input: numerator = -20, denominator = 6

Output: -3

Explanation: -20 / 6 = -3.333..., truncated toward zero is -3.

Example 3

Input: numerator = 231-1, denominator = 1

Output: 2147483647

Explanation: Result is within 32-bit signed integer range.

Example 4

Input: numerator = -231, denominator = -1

Output: 2147483647

Explanation: Result exceeds 32-bit signed integer range, so return 2147483647.

Constraints

  • -231 <= numerator <= 231 - 1
  • -231 <= denominator <= 231 - 1
  • denominator != 0
  • Result must be truncated toward zero
  • Return 231-1 if quotient > 231-1, return -231 if quotient < -231
Python (current runtime)

Case 1

Input: numerator = 25, denominator = 5

Expected: 5

Case 2

Input: numerator = -17, denominator = 2

Expected: -8

Case 3

Input: numerator = 0, denominator = 7

Expected: 0

Case 4

Input: numerator = 100, denominator = -10

Expected: -10

Case 5

Input: numerator = -2**31, denominator = 1

Expected: -2147483648