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.
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 aComplexity Analysis: Time complexity O(1) (constant number of iterations for fixed‑size integers); space complexity O(1).
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.