Skip to main content

Sum of Two Integers

Medium
Data Structures and Algorithms
Editorial
Topics:
Bit Manipulation
Math
Iteration

Implement Solution.getSum(a, b) to compute the arithmetic sum of the two integer parameters a and b. Return that sum as a JSON integer.

The implementation must not use the + or - operators anywhere in the addition logic. Use bitwise operations to reproduce the effects of adding binary digits and propagating carries.

Both positive and negative values are valid, including zero. The returned value must be mathematically equal to a + b, even though the forbidden operators cannot be used.

Example 1:

Input: a = 14, b = -6
Output: 8
Explanation: Adding 14 and -6 produces 8. The method must obtain this result without using the forbidden arithmetic operators.

Example 2:

Input: a = -23, b = 7
Output: -16
Explanation: The negative value has greater magnitude, so the sum is -16.

Example 3:

Input: a = 0, b = 19
Output: 19
Explanation: Adding zero leaves the other integer unchanged.

Constraints:

  • a is an integer.
  • b is an integer.
  • -1000 <= a <= 1000.
  • -1000 <= b <= 1000.
  • The + operator must not be used.
  • The - operator must not be used.

Need help or want more practice?

Practise in an interviewGet AI Coach help