AlgoMaster Logo

Sum of Two Integers

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Iterative Bit Manipulation

The problem states that we need to sum two integers without using the operators + or -. This can be achieved through bit manipulation using the concepts of XOR and carry. Here's the step-by-step breakdown:

  • XOR operation (a ^ b): This operation is like addition but ignores the carry. If only one of the bits is set (either in a or in b, but not both), it will be set in the result.
  • AND operation (a & b): This helps to determine where there would be a carry. When both bits are set (in a and b), a carry is generated.
  • Left shift operation (<<): After identifying the carry bits using AND, they need to be shifted left to add them at the next higher bit position.
  • Repeat this process until there are no carries left to process.

Code:

Example Walkthrough:

Stop when b == 0. Final a = 145 + 9 = 14.

2. Recursive Bit Manipulation

This approach uses the same logic as the iterative approach but utilizes recursion instead.

Code: