Overview
Given two integers a and b, return their sum without using the + or - operators.
Constraints
-1000 <= a, b <= 1000- Must use bitwise operations only.
- JavaScript handles 32-bit integers for bitwise ops.
Examples
getSum(1, 2); // => 3
getSum(-1, 1); // => 0 getSum(0, 0); // => 0
Solution
Reveal solution
function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}XOR gives the sum without carry. AND followed by left-shift gives the carry. Repeat until there is no carry.
Resources
sum-without-addition.js
Sum Without Addition
mediumcodingAlgorithmsBit Manipulation
Overview
Given two integers a and b, return their sum without using the + or - operators.
Constraints
-1000 <= a, b <= 1000- Must use bitwise operations only.
- JavaScript handles 32-bit integers for bitwise ops.
Examples
getSum(1, 2); // => 3
getSum(-1, 1); // => 0 getSum(0, 0); // => 0
Solution
Reveal solution
function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}XOR gives the sum without carry. AND followed by left-shift gives the carry. Repeat until there is no carry.
Resources
NameTopicDifficulty
103 of 103 problems