Show problems as
Classic problem #29MediumMathBit Manipulation

Divide Two Integers

Real-world version: Microcode Divide Step
Tracked in this browser only
Read Divide Two Integers on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

You are writing microcode for a small motor controller. Its arithmetic unit can add, subtract, compare, and shift a register left or right, and that is the whole instruction set: there is no multiply instruction, no divide instruction and nothing that hands back a remainder. The firmware still needs a divide step, so you have to build one.

Given two signed integers value and step, report how many whole steps of size step go into value, carrying the sign the pair of operands implies. Anything left over is thrown away, so the count is cut towards zero and never rounded away from it: 19 over 5 gives 3, and -19 over 5 gives -3.

The result is latched into a signed 32-bit register, which holds values from -2^31 up to 2^31 - 1. Should the cut count sit above that ceiling, latch the ceiling 2^31 - 1 instead; should it sit below the floor, latch the floor -2^31 instead. The caller never passes a step of zero.

Build the count from addition, subtraction, comparison and bit shifts only, the way the unit would. Do not reach for a multiply, divide or remainder operator anywhere in your answer.

Examples

Example 1

Input
value = 23, step = -4
Output
-5

Five steps of size 4 fit inside 23 and 3 is left over. The operands carry opposite signs, so the count is negative and the leftover is discarded: -5.

Example 2

Input
value = -30, step = 7
Output
-4

Four steps of size 7 fit inside 30 with 2 left over, and the opposite signs make the count -4.

Example 3

Input
value = -2147483648, step = -1
Output
2147483647

Two negative operands give an exact count of 2147483648, which is one above what the register holds, so the ceiling 2147483647 is latched.

Constraints

  • -2^31 <= value, step <= 2^31 - 1
  • step != 0

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def microcode_divide_step(value: int, step: int) -> int:
Java
public int microcodeDivideStep(int value, int step)