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
UnverifiedTime 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
- XOR is the sum with no carry.
a & b, shifted left by one, is the carry. Stop when the carry is 0. - Negatives are two’s complement. In Python, mask the carry to 32 bits or the loop does not settle.
a + 0isa.(-1) + 1is 0. At theintboundary the mask is what keeps the carry inside the word.