Divide Two Integers

Given two integers dividend and divisor, divide them without using multiplication, division or the mod operator. The quotient is truncated toward zero, so 8.345 becomes 8 and -2.7335 becomes -2. Assume the environment only stores signed 32-bit integers: if the quotient is above 2^31 - 1 return 2^31 - 1, and if it is below -2^31 return -2^31.

30:00

Divide Two Integers
medium
Free written solution
Topics
Companies

Given two integers dividend and divisor, divide them without using multiplication, division or the mod operator. The quotient is truncated toward zero, so 8.345 becomes 8 and -2.7335 becomes -2. Assume the environment only stores signed 32-bit integers: if the quotient is above 2^31 - 1 return 2^31 - 1, and if it is below -2^31 return -2^31.

Example 1:
Input: {"dividend":10,"divisor":3}
Output: 3
Constraints:
  • −231≤dividend,divisor≤231−1-2^{31} \leq \text{dividend}, \text{divisor} \leq 2^{31} - 1

  • divisor≠0\text{divisor} \neq 0

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"dividend":10,"divisor":3}

Divide 10 by 3 with no *, / or %. The plan: peel off the biggest "divisor times a power of two" that still fits, like long division in binary.

dividend 10
divisor 3
sign ?

|dividend| = ?

a left: ?

nothing subtracted yet

Ladder: b shifted left (b = ?)

Built after taking absolute values.

Variables
VariableValue
dividend10
divisor3
DepthFunction Call
Stack empty
0/9