Problem Statement
Implement the four basic arithmetic operations (+, -, *, /) for integers without using the built-in arithmetic operators.
You may only use:
- Bitwise operators (
&,|,^,~,<<,>>) - Comparison operators
- Loops / recursion
Constraints
- Input integers fit in 32-bit signed range
- Division is integer division (truncate toward zero)
- Division by zero is undefined
- Handle negative numbers correctly
Expected Implementation
add(5, 3) → 8
subtract(10, 4) → 6
multiply(3, 4) → 12
divide(10, 3) → 3
divide(-7, 2) → -3
What the Interviewer Expects
- Addition with bit manipulation:
- XOR gives sum without carry:
a ^ b - AND + left shift gives carry:
(a & b) << 1 - Repeat until carry is 0
- XOR gives sum without carry:
- Subtraction: Negate second operand using two's complement (
~b + 1), then add. - Multiplication: Repeated addition with bit shifting optimization (Russian peasant multiplication).
- Division: Repeated subtraction with bit shifting to speed up (similar to long division in binary).
- Edge cases: Negative numbers, overflow, divide by zero.
Follow-ups
- How do you handle integer overflow in your add function?
- Can you implement modulo (%) using only your divide and multiply?
- What's the time complexity of your multiply and divide implementations?
- How would you extend this to support floating-point arithmetic?