The Sum of Two Integers problem requires adding two integers without using the `+` or `-` operators.

Problem

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

We can solve this problem using bit manipulation. The key idea is to use ^ for addition without carry and & to determine the carry.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

a = 5
b = 3

Output

8

Solution

The XOR operator ^ adds two bits without considering the carry.

For example:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
When both bits are 1, XOR produces 0, but a carry needs to be generated. We can find these carry bits using the AND operator &.
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
The carry must then be shifted one position to the left:
carry = (a & b) << 1
We repeatedly calculate the sum without carry and the carry itself until there is no carry left.
class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            // Calculate the carry.
            int carry = (a & b) << 1;

            // Add without considering the carry.
            a = a ^ b;

            // Process the carry in the next iteration.
            b = carry;
        }

        return a;
    }
}
For example, for a = 5 and b = 3:
a = 0101
b = 0011

a ^ b = 0110
(a & b) << 1 = 0010

a = 0110
b = 0010

a ^ b = 0100
(a & b) << 1 = 0100

a = 0100
b = 0100

a ^ b = 0000
(a & b) << 1 = 1000

a = 0000
b = 1000

a ^ b = 1000
carry = 0000

Result = 1000 = 8

Complexity

The algorithm processes the fixed-size integer bit by bit. For a 32-bit integer, the number of iterations is bounded by a constant, resulting in O(1) time complexity.

Only a constant number of variables is used, resulting in O(1) space complexity.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion