Sum of Two Integers

Adding Two Integers Without Using + or -:

How do you add two integers without using the traditional + or - operators? This intriguing question challenges us to think beyond conventional arithmetic and explore the underlying mechanics of binary operations.

In this article, we’ll break down the problem and walk through an innovative solution.

Pair with given sum - Two Sum

Problem Statement

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

Constraints

  • -1000 <= a, b <= 1000

Explanation:
The sum of 1 and 1 is 2, which can be computed without directly using the + operator.

Explanation:
The sum of 4 and 7 is 11.

Approach: Leveraging Bitwise Operations

To compute the sum of two integers without using + or -, we can take advantage of bitwise operators, specifically AND, XOR, and bit shifting. Here’s how:

Binary Arithmetic Breakdown

In binary, addition is performed digit by digit, just like in decimal arithmetic. The key steps are:

  1. Use the XOR operator (^) to calculate the sum of a and b without considering the carry.
  2. Use the AND operator (&) to calculate the carry bits, which indicate where carry-over is required.
  3. Shift the carry bits left by one position (<<) to align them with the next higher bit for the next addition.
  4. Repeat steps 1-3 until there are no carry bits left.

There are mainly 4 approach to solve this problem – 

  1. Brute Force 
  2. Bit Manipulation 
  3. Bit Manipulation (Optimal)

1. Brute Force 

  • Time complexity: O(1)
  • Space complexity: O(1)

2. Bit Manipulation 

Time & Space Complexity
    • Time complexity: O(1)
    • Space complexity: O(1)

Code

3. Bitmanipulation (Optimal)

  • Time complexity: O(1)
  • Space complexity: O(1)

Code

More Articles