sum-of-two-integers.sh — zsh

Sum of Two Integers

easy
bit-manipulationmath

Given two integers a and b, return their sum without using the + or - operators. Use bitwise operations (AND, OR, XOR, shifts) to simulate addition with carrying instead.

Input / output

  • Input: a: integer, b: integer
  • Output: integer, equal to a + b

Examples

  1. a = 1, b = 2 returns 3.
  2. a = 2, b = 3 returns 5.
  3. a = -2, b = 3 returns 1.

Constraints

  • -1,000 <= a, b <= 1,000

Follow-up Can you explain why a XOR b gives the sum without carries, and (a AND b) << 1 gives exactly the carries that must be added back in, repeating until there is no carry left?

Examples
Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = 2, b = 3
Output: 5
Example 3 (negative operand)
Input: a = -2, b = 3
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.