KatInterview

Bitwise Quotient Without Multiply, Divide, or Modulo

Math & Bit ManipulationAuto-graded · 25 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationmathbinary-search

Last updated

Compute a truncated 32-bit signed integer quotient using only shifts, addition and subtraction, handling the single overflow case and sign rules efficiently.

Quotient Without Arithmetic Division

You are given two integers, numerator and denominator, both within the range of a 32-bit signed integer. Compute the integer quotient of numerator divided by denominator.

You may not use the multiplication operator *, the division operators / or //, or the modulo operator %. Shifts, addition, subtraction, comparisons and negation are all allowed.

Rules

  • The quotient is truncated toward zero. For example, 7 / -3 gives -2, and -7 / 3 gives -2 (not -3).
  • denominator is never zero.
  • If the true quotient falls outside the signed 32-bit range, return 2147483647 (that is, 2^31 - 1). Note that a result of exactly -2^31 is within range and must be returned unchanged.
  • Your solution should be much faster than removing the denominator from the numerator one copy at a time. A running time proportional to the number of bits is expected.

Task

Implement int_quotient(numerator, denominator) that returns the truncated quotient as an integer, following the rules above.

Constraints

  • -2^31 <= numerator <= 2^31 - 1
  • -2^31 <= denominator <= 2^31 - 1
  • denominator != 0
  • The operators *, /, // and % must not be used (and neither should divmod, pow-based tricks, or float division).

Examples

Example 1

Input: int_quotient(10, 3)

Output: 3

Example 2

Input: int_quotient(7, -3)

Output: -2

Example 3

Input: int_quotient(-7, 3)

Output: -2

Example 4

Input: int_quotient(-2147483648, -1)

Output: 2147483647

Hints

Hint 1

Removing the denominator one copy at a time is far too slow for inputs like -2^31 divided by 1. Think about removing big chunks: a denominator shifted left by k bits equals denominator times 2^k.

Hint 2

Work with absolute values and apply the sign at the end. Then, for each bit position from high to low, check whether the shifted denominator still fits in what remains of the numerator; if so, subtract it and record that bit in the answer.

Hint 3

Only one input pair can overflow: -2^31 divided by -1. Handle it before anything else, and be careful not to clamp -2^31 divided by 1, which is a valid result.