> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Sum of Two Integers

Leetcode Problem 371: Sum of Two Integers

Problem Summary

Given two integers a and b, return their sum without using the + or - operators.

Constraints:

  • Both a and b are integers in the range [-1,000, 1,000].

Techniques

  • Math
  • Bit Manipulation

Solution

// Well, this is quite a bit of a challenge. 
// After getting the general approach, i was getting lost in the loop with temp variables....
function getSum(a: number, b: number): number {
    let carry = a & b
    let sum = a ^ b

    while (carry) {
        let carryShift = carry << 1
        carry = sum & carryShift
        sum = sum ^ carryShift
    }

    return sum
};

console.log(getSum(3, 2))