Quick Overview

This question evaluates proficiency in bitwise arithmetic, integer overflow semantics, sign handling, and algorithmic efficiency for implementing multiplication without using multiplication or division operators.

Implement multiplication without using the multiplication operator

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Implement int multiply(int a, int b) without using * or /. You may use +, −, bitwise operators, and shifts. Requirements: - Handle negatives, zero, and the corner case INT_MIN * −1. - Achieve O(log |b|) additions via shift‑and‑add (Russian peasant), not naive O(|b|) repeated addition. - Assume 32‑bit signed ints. First implement unchecked overflow (two’s‑complement wrap), then a safe version that saturates to INT_MAX/INT_MIN on overflow without using 64‑bit types. - Analyze time and space complexity and prove correctness for all sign combinations. - Provide unit tests: 0×x, 1×x, −1×x, powers of two, random pairs, INT_MAX×2, INT_MIN×2, INT_MIN×−1. Follow‑ups: how would you extend to big integers and compare with Karatsuba? What changes if the platform lacks arithmetic right shift?

Quick Answer: This question evaluates proficiency in bitwise arithmetic, integer overflow semantics, sign handling, and algorithmic efficiency for implementing multiplication without using multiplication or division operators.

Unchecked 32-bit Multiply Without *

Return a*b using shift-and-add with two-complement 32-bit wraparound.

Constraints

  • Inputs are Python literals matching the function signature.
  • Return a deterministic exact-match value.

Examples

Input: (3, 5)

Expected Output: 15

Explanation: Positive values.

Input: (-7, 6)

Expected Output: -42

Explanation: Negative sign.

Hints

  1. Choose a representation that makes the requested operation direct.
  2. Handle empty inputs and boundary cases first.

Saturating 32-bit Multiply Without *

Return a*b using shift-and-add, saturating to INT_MAX or INT_MIN on overflow.

Constraints

  • Inputs are Python literals matching the function signature.
  • Return a deterministic exact-match value.

Examples

Input: (3, 5)

Expected Output: 15

Explanation: Positive values.

Input: (-7, 6)

Expected Output: -42

Explanation: Negative sign.

Hints

  1. Choose a representation that makes the requested operation direct.
  2. Handle empty inputs and boundary cases first.

Loading coding console...