Fundamentals 4 min read

Sum of Two Integers Without Using + or - Operators

The problem asks to add two integers without using '+' or '-', which is solved by repeatedly applying bitwise XOR to obtain the sum without carry and left‑shifted AND to compute the carry until it vanishes, as demonstrated in concise Java and Python implementations with O(1) time and space complexity.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Sum of Two Integers Without Using + or - Operators

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

Example 1: Input: a = 1, b = 2 → Output: 3

Example 2: Input: a = 2, b = 3 → Output: 5

Solution Idea: Use bitwise operations. The XOR of a and b gives the sum without carry, while the AND (shifted left) gives the carry. Repeat until the carry becomes zero.

Java implementation:

class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int temp = a ^ b;
            b = (a & b) << 1;
            a = temp;
        }
        return a;
    }
}

Python implementation:

class Solution:
    def getSum(self, a: int, b: int) -> int:
        while b != 0:
            temp = a ^ b
            b = (a & b) << 1
            a = temp
        return a

Complexity Analysis: Time complexity O(1) (constant number of iterations for fixed‑size integers); space complexity O(1).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmbitwiseno-plus-minus
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.