Problem
Implement basic integer arithmetic operations using only bitwise operators and shifts. Specifically, provide correct implementations (and explain the ideas) for:
- Addition of two signed integers without using
+
. - Subtraction of two signed integers without using
-
. - Multiplication of two integers using only shifts and additions.
- Integer division (quotient and remainder) using only shifts and subtraction.
Preserve integer semantics (two’s complement for negatives) and handle edge cases such as zero and divide-by-zero where applicable. The file contains several related wiki links to worked articles and variations of these problems.
Solution
Method 1 — Using Bitwise Operators
Addition
Addition can be implemented using bitwise XOR for the partial sum and bitwise AND (shifted) for carries. Repeating these steps until there are no carries yields the final sum. We have covered it here - Sum of two numbers using only bitwise operators.
Subtraction
Subtraction can be reduced to addition via two’s complement: a - b == a + (~b + 1)
. Here is the detailed solution - Subtract Two Numbers Without Using Arithematic Operators.
Multiplication
Multiply by decomposing the multiplier into bits. Shift the multiplicand and conditionally add when a multiplier bit is set. We have covered it here - Multiply Two Numbers using Bitwise Operators.
Division
Find the largest shifts of divisor that fit into dividend, subtract and accumulate corresponding powers of two into the quotient. We have covered this one here - Divide Two Integers.