Ctrl K

Division Without Dividing

Medium
You are given two integers top and bottom. Return the quotient top / bottom with the fractional part dropped (rounded toward zero): for example, 4.9 becomes 4 and -4.9 becomes -4. You may not use multiplication, division or the remainder operator: only addition, subtraction, comparisons and bit shifts. Assume the result must fit in a 32-bit signed integer: if the quotient is above 2³¹ − 1, return 2³¹ − 1, and if it is below -2³¹, return -2³¹.
Example 1
top=17, bottom=5 → 3

17 / 5 = 3.4; dropping the fractional part gives 3.

Example 2
top=-20, bottom=6 → -3

-20 / 6 ≈ -3.33; truncating toward zero gives -3.

Example 3
top=-2147483648, bottom=-1 → 2147483647

The exact answer 2³¹ is out of range, so the result is clamped to 2³¹ − 1 = 2147483647.

Constraints
  • -2³¹ ≤ top, bottom ≤ 2³¹ − 1
  • bottom ≠ 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMirrored One-Bit Codes MediumAdding Without a Plus MediumShared Pool Race to a Goal MediumSum of Bit Differences MediumA Four-Button Lamp Panel Medium
loading Python…
Input
top=17, bottom=5
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 137 tests on the server, hidden ones included.