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).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
