Add two numbers without using the plus operator
HardUpdated: Sep 18, 2025
Problem
Implement a function Add(a, b) that returns the sum of two integers without using the arithmetic + operator (or any direct arithmetic increment/decrement). Use bitwise operations to produce the result.
This is very similar to [Sum of Two Integers](sum-of-two-integers), but here - operator is allowed.
Examples
Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = -2, b = 3
Output: 1
Solution
Method 1 — Bitwise addition (half-adder style)
We can use half adder solution - [Sum of two numbers using only bitwise operators](sum-of-two-numbers-using-only-bitwise-operators).
Method 2 — Using subtraction and negation
Intuition
Adding b to a is equivalent to subtracting the negation of b from a: a + b = a - (-b). If the problem constraint only forbids the + operator (and not - or unary negation), this identity gives a very short alternative.
Approach
- Compute
neg_b = -busing the language's unary negation. - Return
a - neg_b.
Edge cases:
- This uses the subtraction operator; if the problem forbids all arithmetic operators then this method is not allowed.
- Be cautious of overflow in fixed-width integer types when negating the most-negative value (e.g.,
INT_MIN).
Code
C++
class Solution {
public:
static int add(int a, int b) {
int neg_b = -b;
return a - neg_b;
}
};
Go
package main
func Add(a, b int) int {
negB := -b
return a - negB
}
Java
class Solution {
public static int add(int a, int b) {
int negB = -b;
return a - negB;
}
}
Python
class Solution:
@staticmethod
def add(a: int, b: int) -> int:
neg_b = -b
return a - neg_b
Complexity
- ⏰ Time complexity:
O(1)— constant time arithmetic operations. - 🧺 Space complexity:
O(1)extra space.