Mediumbit-manipulation
Sum of Two Integers
Problem (restated)
Return a+b without using + or, operators.
Intuition
a^b is sum without carry; (a&b)<<1 is carry. Iterate until carry is 0.
Approaches
XOR + carry loop
Tested onlyTime O(1) 32-bitSpace O(1)
Idea. Full-adder simulation over bits. Python needs 32-bit mask for negatives.
Walkthrough. 1+2 → 3; -1+1 → 0.
Trade-offs. Built-in + is fine in production; problem is a bit-op exercise.
Solution
export function getSum(a: number, b: number): number {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
// JS bitwise is 32-bit signed already for |0
return a | 0;
}
export function getSum(a: number, b: number): number {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
// JS bitwise is 32-bit signed already for |0
return a | 0;
}
Template connection
Bitwise arithmetic simulation.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?