0010 (2)
a
Add two integers without using + or - by simulating a hardware adder: XOR computes the sum-without-carry each round, while (a & b) << 1 propagates the carry until it vanishes.
Return the sum of two integers without using + or -. For example, getSum(2, 3) should return 5. In binary: 010 ^ 011 = 001 (partial sum), (010 & 011) << 1 = 100 (carry), then 001 ^ 100 = 101 = 5.
<< 1) so it lands in the correct column, then repeat. This is exactly what transistors do inside a CPU.carry = (a & b) << 1 — AND finds positions where both bits are 1 (a carry will propagate into the next column), shift left to align it.a = a ^ b — XOR adds each bit pair ignoring carries.b = carry— carry is now the new "thing to add".b === 0 there is nothing left to add; a holds the final answer.a. If you write a = a ^ b first, the old value of a is lost and (a & b) gives a wrong carry.The loop runs at most as many times as there are bit-width positions (32 for a 32-bit integer). In the worst case every iteration generates another carry, but the carry shifts left each time, so it must reach zero within 32 steps.
a=2 and b=3. We'll add using only bit operations: XOR computes sum-without-carry, (AND)<<1 computes the carry.function getSum(a: number, b: number): number {
while (b !== 0) {
const carry = (a & b) << 1; // bits where both are 1 → shift left
a = a ^ b; // XOR: add without carry
b = carry; // carry becomes the new b
}
return a;
}b (carry) reaches zero, the partial sum stored in a is the final answer.(a & b) << 1 identifies bit positions where both values have a 1 (those columns will carry) and shifts the result one column to the left. Computed before we modify a.a ^ b sets each bit where exactly one of a or b is 1 — binary addition ignoring carries. We reassign a to this value.b = carry. The carry now becomes the next value to add. On the next iteration XOR will fold it in and AND will find any new carries from it.b === 0 means no carry remains. a is the complete sum. Return it.a with the XOR result, the original bits are gone and we can no longer compute the correct AND.getSum(a^b, (a&b)<<1) with base case b===0. Same logic, tail-recursive.a stays 0 and we return 0 immediately.b strictly increases. After 32 shifts at most, it falls off the word and becomes 0.| "no + or − operator" | XOR for bits, (AND)<<1 for carry |
| hardware adder / ripple carry | while (b) { carry=(a&b)<<1; a^=b; b=carry } |
| bit-level addition in a loop | carry shifts left, terminates in ≤32 steps |
| "sum without arithmetic" | same pattern: XOR = diff, AND<<1 = borrow-or-carry |
function getSum(a: number, b: number): number {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}a ^ b represent in each iteration?(a & b) << 1 represent?