32-Bit Integer Product via Shift-and-Add
Math & Bit ManipulationAuto-graded · 28 test casesLast updated
Tests mastery of bitwise arithmetic, sign handling, two's-complement overflow semantics, and O(log n) shift-and-add multiplication without using * or /.
32-Bit Integer Product via Shift-and-Add
You must compute the product of two 32-bit signed integers without using the * or / operators at any point in your implementation.
Your function receives two integers a and b (each guaranteed to fit in a 32-bit signed type) and a boolean flag clamp. It returns their product interpreted under 32-bit signed arithmetic, with behavior controlled by clamp.
Core algorithm
Decompose the magnitude of b into its binary representation. The product |a| × |b| equals the sum of |a| × 2ⁱ for every bit position i where b has a 1. Start with an accumulator at 0 and a running term equal to |a|. On each iteration, if the current low bit of |b| is set, add the running term to the accumulator; then shift |b| right by one and double the running term (via self-addition). This is equivalent to the classical Russian peasant algorithm and runs in O(log |b|) additions.
Determine the sign of the result separately: the product is negative exactly when one input is negative and the other is not. Multiply magnitudes, then apply the sign.
Two modes
Unchecked mode (clamp=False)
Simulate 32-bit two's-complement wraparound. Reduce every intermediate value modulo 2³² using a bitmask. After the magnitude loop, negate if necessary (also under the mask), then reinterpret the 32-bit pattern as a signed integer. Do not use any 64-bit integer type.
Saturating mode (clamp=True)
Instead of wrapping, pin the result to the nearest representable boundary when the true product would overflow:
- Return
INT_MAX(2³¹ − 1) if the result would exceed it. - Return
INT_MIN(−2³¹) if the result would fall below it.
To detect overflow without ever forming an oversized value, compare before adding: if addend > limit − result, the addition would overflow, so saturate immediately. Use an appropriate limit based on the sign of the final result:
- Positive results:
limit = INT_MAX = 2³¹ − 1 - Negative results:
limit = 2³¹(because|INT_MIN| = 2³¹, one more thanINT_MAX)
When doubling the running term, check whether it would exceed limit before doing so. If it would, assign it a sentinel value of limit + 1; any future use of this sentinel correctly triggers saturation. Do not use any 64-bit integer type.
Constraints
-2³¹ ≤ a, b ≤ 2³¹ − 1(standard 32-bit signed range)clampis a plain Pythonbool- Do not use
*or/anywhere in your implementation - Do not use 64-bit integer types (no
numpy.int64, no intermediate Python ints wider than 32 bits for the saturating path — rely on the pre-addition check instead) - Your solution must run in O(log |b|) time, not O(|b|)
0 × xandx × 0must return0for allx, including negative valuesINT_MIN × −1wraps toINT_MINin unchecked mode and saturates toINT_MAXin saturating mode
Examples
Example 1
Input: multiply_32(0, 12345, False)
Output: 0
Example 2
Input: multiply_32(7, 6, False)
Output: 42
Example 3
Input: multiply_32(-7, 6, False)
Output: -42
Example 4
Input: multiply_32(-7, -6, False)
Output: 42
Example 5
Input: multiply_32(2147483647, 2, False)
Output: -2
Example 6
Input: multiply_32(-2147483648, -1, False)
Output: -2147483648
Example 7
Input: multiply_32(2147483647, 2, True)
Output: 2147483647
Example 8
Input: multiply_32(-2147483648, -1, True)
Output: 2147483647
Hints
Hint 1
Separate sign from magnitude at the start. Determine whether the result is negative by checking if exactly one input is negative, then work entirely with non-negative magnitudes until the very end.
Hint 2
In unchecked mode, apply a 32-bit mask `(1 << 32) - 1` after every addition and every left-shift to keep values from growing beyond 32 bits. Negate the final magnitude under the same mask before reinterpreting it as signed.
Hint 3
In saturating mode, set `limit = INT_MAX` for a positive result and `limit = 2³¹` for a negative one. Before each addition, check `addend > limit - result` to detect overflow without actually computing the sum. When doubling the running term, apply the same style of pre-check and assign a sentinel if it would exceed the limit.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sign and magnitude separation
The sign of a product depends only on whether the two inputs have opposite signs. Compute that flag up front: negative = (a < 0) != (b < 0). Then strip signs and work with magnitude_a and magnitude_b throughout the loop. Apply the sign once at the very end.
This cleanly handles all four sign combinations and the zero case — when either magnitude is zero the loop body never executes, so result stays at 0, and -0 == 0.
The shift-and-add loop
Write magnitude_b in binary: magnitude_b = Σ bᵢ · 2ⁱ. Then:
magnitude_a × magnitude_b = Σ bᵢ · (magnitude_a · 2ⁱ)
The loop maintains:
resultaccumulates the partial sum for bits already processed.addendequalsmagnitude_a · 2ⁱfor the current iterationi(doubled by self-addition, no*needed).multiplierholds the remaining unprocessed bits ofmagnitude_b.
Each iteration: if the low bit of multiplier is 1, add addend to result; then right-shift multiplier and double addend. The loop ends when multiplier reaches 0, at which point result = magnitude_a × magnitude_b.
Unchecked mode (clamp=False)
Apply & MASK (where MASK = 2³² − 1) after every addition and every left-shift. This keeps every intermediate value inside a 32-bit window, simulating two's-complement hardware. After the loop, negate under the mask if the result is negative, then reinterpret the bit pattern as a signed value by subtracting 2³² if it is ≥ 2³¹.
Since reduction mod 2³² commutes with addition and negation, the final bit pattern equals what a 32-bit ALU would produce. In particular, INT_MIN × −1 wraps back to INT_MIN.
Saturating mode (clamp=True)
Instead of masking, detect overflow before each addition using the identity: result + addend > limit iff addend > limit - result. This check never forms the overflowing sum, so no wider integer type is ever needed.
The limit for the magnitude is:
INT_MAX = 2³¹ − 1for a positive final result.2³¹for a negative final result, because|INT_MIN| = 2³¹is a valid magnitude.
When doubling addend, apply the same style of pre-check. If doubling would exceed limit, assign the sentinel limit + 1. Any future use of the sentinel satisfies addend > limit - result (since result ≥ 0), correctly triggering saturation. Doubling the sentinel keeps it at limit + 1.
Guard the doubling step with if multiplier: — only double when at least one more bit remains to be processed. This prevents a spurious saturation on the final iteration.
Correctness on edge cases
| Input | Unchecked | Saturating |
|---|---|---|
0 × x | 0 | 0 |
INT_MIN × −1 | INT_MIN (wraps) | INT_MAX |
INT_MIN × 1 | INT_MIN | INT_MIN |
INT_MAX × 2 | −2 (wraps) | INT_MAX |
INT_MIN × 2 | 0 (wraps) | INT_MIN |
Complexity
- Time: O(log |b|) — the loop executes at most 31 iterations for 32-bit inputs, each doing O(1) work.
- Space: O(1) — a fixed number of scalar variables, no auxiliary data structures.
Full solution
MASK = (1 << 32) - 1
SIGN_BIT = 1 << 31
MODULUS = 1 << 32
INT_MAX = (1 << 31) - 1
INT_MIN = -(1 << 31)
def multiply_32(a: int, b: int, clamp: bool) -> int:
negative = (a < 0) != (b < 0)
magnitude_a = -a if a < 0 else a
magnitude_b = -b if b < 0 else b
if clamp:
# Limit for the magnitude: 2^31 for negative results, INT_MAX for positive.
limit = SIGN_BIT if negative else INT_MAX
result = 0
addend = magnitude_a
multiplier = magnitude_b
while multiplier:
if multiplier & 1:
if addend > limit - result: # addition would exceed limit
return INT_MIN if negative else INT_MAX
result += addend
multiplier >>= 1
if multiplier: # only double if the term may be used again
if addend > limit - addend:
addend = limit + 1 # sentinel: marks addend as "already too large"
else:
addend += addend
return -result if negative else result
# Unchecked two's-complement wraparound path
result = 0
addend = magnitude_a & MASK
multiplier = magnitude_b
while multiplier:
if multiplier & 1:
result = (result + addend) & MASK
multiplier >>= 1
addend = (addend << 1) & MASK
if negative:
result = (-result) & MASK
if result >= SIGN_BIT: # reinterpret as signed
result -= MODULUS
return result