Divide Two Integers

MediumBit Manipulationbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given two integers dividend and divisor, return their quotient **without** using multiplication, division, or the modulo operator. The quotient is truncated toward zero, so 8.7 becomes 8 and -2.7 becomes -2. Treat the values as signed 32-bit integers. If the true quotient is larger than 2^31 - 1, return 2^31 - 1; if it is smaller than -2^31, return -2^31. (The only case that overflows is -2^31 / -1.) divisor is never 0. Aim for a solution that runs in O(log^2 n) or better rather than subtracting the divisor one step at a time.

Examples

Input: dividend = 10, divisor = 3
Output: 3
10 / 3 = 3.33..., which truncates to 3.
Input: dividend = 7, divisor = -3
Output: -2
7 / -3 = -2.33..., which truncates toward zero to -2.
Input: dividend = -2147483648, divisor = -1
Output: 2147483647
The true answer 2^31 does not fit, so it is clamped to 2^31 - 1.

Constraints

  • -2^31 <= dividend, divisor <= 2^31 - 1
  • divisor != 0

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems