A friend and I are going back and forth with brainteasers and I have no idea how to solve this one. My assumption is that it's possible with some bitwise operators, but not sure.

2You can look at each bit by having a loop that >> until the value is 0 (THen you will have processed all of the bits). Cast it to unsigned first. Do I win a prize?– Andrew RollingsDec 13 '08 at 18:29

1Thank you. Your reward is the knowledge that you helped a lady in distress.– user23126Dec 13 '08 at 18:41

1If NO operators can be used, aren't bitwise operators ruled out then too? Or just +*/ ?– VilxDec 13 '08 at 19:04

1an abacus will do this quite well, and it doesn't use any electricity!– Steven A. LoweDec 13 '08 at 20:04

3i'm going to use std::plus<int>()(a, b)– Johannes Schaub  litbDec 13 '08 at 20:08
In C, with bitwise operators:
#include<stdio.h>
int add(int x, int y) {
int a, b;
do {
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a);
return b;
}
int main( void ){
printf( "2 + 3 = %d", add(2,3));
return 0;
}
XOR (x ^ y
) is addition without carry. (x & y)
is the carryout from each bit. (x & y) << 1
is the carryin to each bit.
The loop keeps adding the carries until the carry is zero for all bits.

Thank you. I am afraid to ask, but does subtraction work similarly? I read that I can just add the two's complement. But when I try to, say, subtract 63, and turn that into 6+(3) using two's complement, I get an infinite loop in the above algorithm. Dec 13 '08 at 18:39

1add(6, 3) should work, you can play with the code here: codepad.org/iWSRSsUn Dec 13 '08 at 18:43

8Left shifting a negative value is undefined behavior, it will work as expected on many processors but it isn't guaranteed, you should point this out in your answer. Also, can you add a \n to your printf statement? Aside from that, nice answer. Dec 13 '08 at 19:23

I tried converting your algorithm into Python (codepad.org/pb8IuLnY) and am experiencing an infinite loop when a negative number is passed in (i.e. the subtract). Are Python's operators any different than C? Dec 13 '08 at 20:13

1@pomeranian.myopenid.com, it is most likely due to the way the leftshift operator is handled in Python. Instead of reaching an upper limit on the integer bits, and setting the highest bit to make a number negative, it becomes positive long integers. Dec 14 '08 at 18:24
int add(int a, int b) {
const char *c=0;
return &(&c[a])[b];
}

3I didn't quite understand how this one works, an explanation would be great! Oct 24 '13 at 23:21

6@ffledgling The address of
c
is initially 0. The address ofc[a]
is0 + a = a
. And the address of(&c[a])[b]
isa + b
. Nice cheat, though stilladd
is implicitly used.– LandysSep 3 '14 at 3:24 
2Note that you need to allocate an array large enough for the largest sum. Otherwise, creating a pointer that exceeds an array bounds is undefined behavior.– NayukiJul 3 '16 at 5:17

No + right?
int add(int a, int b)
{
return (a)  (b);
}

8In the question comments, @pomeranian.myopenid.com mentions that no arithmetic operators can be used. Besides, it would be better put as a  (b) to use subtraction as the substitute operation. Dec 13 '08 at 19:17
CMS's add() function is beautiful. It should not be sullied by unary negation (a nonbitwise operation, tantamount to using addition: y==(~y)+1). So here's a subtraction function using the same bitwiseonly design:
int sub(int x, int y) {
unsigned a, b;
do {
a = ~x & y;
b = x ^ y;
x = b;
y = a << 1;
} while (a);
return b;
}

This does not provide an answer to the question, which is asking for addition, not subtraction.– MD XFOct 3 '17 at 1:04

@MD XF, I was providing an answer to a question user23126 asked in the comments of CMS's answer. I felt CMS's answer to this comment was unsatisfactory, since as I explained above, unary negation is tantamount to using addition. There is no way to put multiline code in a comment, so I posted it as an answer. Also note that user23126 was the original question asker – so in a way, this does qualify as answering the question.– DeadcodeDec 8 '18 at 4:24

Also, while the question does literally ask how to add two numbers without using the + operator, it's trivially possible with
a  (b)
as others stated. So answering how to do it without using any arithmetic operators is more in the spirit of the question. Also, user23126 directly stated that an operator which isn't literally+
still isn't acceptable to use if it does addition, and++
is very similar to part of what negation does behind the scenes.– DeadcodeDec 8 '18 at 4:43
Define "best". Here's a python version:
len(range(x)+range(y))
The +
performs list concatenation, not addition.

1
without using the + operator
 doesn't saywithout using the addition operator
.– MD XFSep 26 '17 at 3:40 
Java solution with bitwise operators:
// Recursive solution
public static int addR(int x, int y) {
if (y == 0) return x;
int sum = x ^ y; //SUM of two integer is X XOR Y
int carry = (x & y) << 1; //CARRY of two integer is X AND Y
return addR(sum, carry);
}
//Iterative solution
public static int addI(int x, int y) {
while (y != 0) {
int carry = (x & y); //CARRY is AND of two bits
x = x ^ y; //SUM of two bits is X XOR Y
y = carry << 1; //shifts carry to 1 bit to calculate sum
}
return x;
}

1

1This is exactly CMS's answer (the currently accepted one), but with meaningful variable names, and an explanation with inline comments instead of in the text (which CMS's answer was missing for years, but I added it in July 2016.) Still, upvoted for explaining it clearly and correctly. Oct 3 '17 at 1:24

Actually, it would be better to say that
xor
is addwithoutcarry. The first comment in the recursive version says it's the sum of two integers, which is wrong. Oct 3 '17 at 1:27 
@PeterCordes CMS's answer includes a main method and is valid C code. What I have added here is valid Java methods only. This code is tested on my local machine and not directly copy pasted from other source. Thanks for your comments though.– realPKOct 3 '17 at 7:03
Cheat. You could negate the number and subtract it from the first :)
Failing that, look up how a binary adder works. :)
EDIT: Ah, saw your comment after I posted.
Details of binary addition are here.


The link is broken and the rest of this answer is invalid; it should be deleted.– MD XFOct 3 '17 at 1:05

The link is corrected, and the answer is relevant is the context of the comments on the original question. Oct 3 '17 at 1:11
Note, this would be for an adder known as a ripplecarry adder, which works, but does not perform optimally. Most binary adders built into hardware are a form of fast adder such as a carrylookahead adder.
My ripplecarry adder works for both unsigned and 2's complement integers if you set carry_in to 0, and 1's complement integers if carry_in is set to 1. I also added flags to show underflow or overflow on the addition.
#define BIT_LEN 32
#define ADD_OK 0
#define ADD_UNDERFLOW 1
#define ADD_OVERFLOW 2
int ripple_add(int a, int b, char carry_in, char* flags) {
int result = 0;
int current_bit_position = 0;
char a_bit = 0, b_bit = 0, result_bit = 0;
while ((a  b) && current_bit_position < BIT_LEN) {
a_bit = a & 1;
b_bit = b & 1;
result_bit = (a_bit ^ b_bit ^ carry_in);
result = result_bit << current_bit_position++;
carry_in = (a_bit & b_bit)  (a_bit & carry_in)  (b_bit & carry_in);
a >>= 1;
b >>= 1;
}
if (current_bit_position < BIT_LEN) {
*flags = ADD_OK;
}
else if (a_bit & b_bit & ~result_bit) {
*flags = ADD_UNDERFLOW;
}
else if (~a_bit & ~b_bit & result_bit) {
*flags = ADD_OVERFLOW;
}
else {
*flags = ADD_OK;
}
return result;
}

Unfortunately the increment operator (current_bit_position++) requires addition. Nitpicky, I know. Dec 14 '08 at 16:50

2@pomeranian.myopenid.com yeah, that is true in this case. In hardware, there is separate logic gates for each bit, and doesn't use a loop. If this loop were to be unrolled, you could use it without the ++ operator. Dec 14 '08 at 18:17

@Lara: Yes, unroll. For 32 bits it would be 32 copies of the code within the whileloop. This would give a nice hardware pseudocode and a bonus point: it is even executable! Programming hardware follows different rules than programming software, so some best practices don't apply here...– nalplySep 20 '11 at 11:39
Go based solution
func add(a int, b int) int {
for {
carry := (a & b) << 1
a = a ^ b
b = carry
if b == 0 {
break
}
}
return a
}
same solution can be implemented in Python as follows, but there is some problem about number represent in Python, Python has more than 32 bits for integers. so we will use a mask to obtain the last 32 bits.
Eg: if we don't use mask we won't get the result for numbers (1,1)
def add(a,b):
mask = 0xffffffff
while b & mask:
carry = a & b
a = a ^ b
b = carry << 1
return (a & mask)

It'd be simpler to just
return a&mask
. Checking to see if you might not need to just complicates the code, and&
is cheap. Oct 13 '19 at 16:52
Why not just incremet the first number as often, as the second number?


not really, INC and ADD are to different opcodes in machine language ;)– sindre jDec 13 '08 at 23:21
The reason ADD is implememted in assembler as a single instruction, rather than as some combination of bitwise operations, is that it is hard to do. You have to worry about the carries from a given low order bit to the next higher order bit. This is stuff that the machines do in hardware fast, but that even with C, you can't do in software fast.

If you manage to write something in C that exactly matches what a hardware
add
instruction does for all inputs that don't cause undefined behaviour, the compiler can use anadd
. We're in exactly that situation now for things likepopcnt
, where the only pure ISO C way to get apopcnt
instruction is for the compiler to recognize an idiom and optimize your loop or bithack sequence into apopcnt
(and yes compilers will do that). Or for a rotate. stackoverflow.com/questions/776508/…. Oct 3 '17 at 1:30 
Obviously having a
+
operator in C is vastly better than the alternative, but ugly source would be the main problem, not slow code. Heh, orfoo = (int) &((char*)x)[y]
to use arrayindex syntax as a+
operator, but even creating a bogus pointer is UB in C. Oct 3 '17 at 1:32
Here's a portable oneline ternary and recursive solution.
int add(int x, int y) {
return y == 0 ? x : add(x ^ y, (x & y) << 1);
}
I saw this as problem 18.1 in the coding interview. My python solution:
def foo(a, b):
"""iterate through a and b, count iteration via a list, check len"""
x = []
for i in range(a):
x.append(a)
for i in range(b):
x.append(b)
print len(x)
This method uses iteration, so the time complexity isn't optimal. I believe the best way is to work at a lower level with bitwise operations.
In python using bitwise operators:
def sum_no_arithmetic_operators(x,y):
while True:
carry = x & y
x = x ^ y
y = carry << 1
if y == 0:
break
return x

this will error out for pairs (1,1) , we have to use a mask to get the last 32 bits stackoverflow.com/questions/365522/… Oct 13 '19 at 16:39
Adding two integers is not that difficult; there are many examples of binary addition online.
A more challenging problem is floating point numbers! There's an example at http://pages.cs.wisc.edu/~smoler/x86text/lect.notes/arith.flpt.html
Was working on this problem myself in C# and couldn't get all test cases to pass. I then ran across this.
Here is an implementation in C# 6:
public int Sum(int a, int b) => b != 0 ? Sum(a ^ b, (a & b) << 1) : a;


That is what I thought too, but that answer didn't pass all the test cases I had. So I offered what ended up working for me in a different programming language. Sometimes people happen upon questions long after they were posted and are in slightly different situations than the original poster. I hoped to help someone in a situation similar to the one I was. Sorry if I offended you, and feel free to edit my answer as well if you feel the need. Jul 6 '16 at 15:09

I didn't look closely; how is your algo different from CMS's? Your recursionend check is slightly different. Oh, should CMS's function check
while(x)
instead ofwhile(a)
? Anyway, if there's a problem with the accepted answer, you should comment on that either as a comment or as part of the text of this answer (or both). Anyway, I'm not personally offended, I just didn't think this answer was adding much value since what looks like the same algo was already posted. Jul 6 '16 at 15:17 
There isn't a problem with it. It just doesn't translate to C# without augmentation. I think the key is a difference in language. I don't think negatives being shifted behave the same. In fact shifted negatives shouldn't guarantee that negatives be treated correctly in a mathematical sense because that's not the essence of a bit shift. My answer is specifically geared towards C# implementers and burying a comment that includes a solution that is different might get missed by someone that could be helped by this answer. Jul 6 '16 at 15:50
Implemented in same way as we might do binary addition on paper.
int add(int x, int y)
{
int t1_set, t2_set;
int carry = 0;
int result = 0;
int mask = 0x1;
while (mask != 0) {
t1_set = x & mask;
t2_set = y & mask;
if (carry) {
if (!t1_set && !t2_set) {
carry = 0;
result = mask;
} else if (t1_set && t2_set) {
result = mask;
}
} else {
if ((t1_set && !t2_set)  (!t1_set && t2_set)) {
result = mask;
} else if (t1_set && t2_set) {
carry = 1;
}
}
mask <<= 1;
}
return (result);
}
Improved for speed would be below::
int add_better (int x, int y)
{
int b1_set, b2_set;
int mask = 0x1;
int result = 0;
int carry = 0;
while (mask != 0) {
b1_set = x & mask ? 1 : 0;
b2_set = y & mask ? 1 : 0;
if ( (b1_set ^ b2_set) ^ carry)
result = mask;
carry = (b1_set & b2_set)  (b1_set & carry)  (b2_set & carry);
mask <<= 1;
}
return (result);
}
It is my implementation on Python. It works well, when we know the number of bytes(or bits).
def summ(a, b):
#for 4 bytes(or 4*8 bits)
max_num = 0xFFFFFFFF
while a != 0:
a, b = ((a & b) << 1), (a ^ b)
if a > max_num:
b = (b&max_num)
break
return b
You can do it using bitshifting and the AND operation.
#include <stdio.h>
int main()
{
unsigned int x = 3, y = 1, sum, carry;
sum = x ^ y; // Ex  OR x and y
carry = x & y; // AND x and y
while (carry != 0) {
carry = carry << 1; // left shift the carry
x = sum; // initialize x as sum
y = carry; // initialize y as carry
sum = x ^ y; // sum is calculated
carry = x & y; /* carry is calculated, the loop condition is
evaluated and the process is repeated until
carry is equal to 0.
*/
}
printf("%d\n", sum); // the program will print 4
return 0;
}

A
do{}while()
loop is actually easier here, like the currently accepted answer does. May 28 '20 at 20:14
The most voted answer will not work if the inputs are of opposite sign. The following however will. I have cheated at one place, but only to keep the code a bit clean. Any suggestions for improvement welcome
def add(x, y):
if (x >= 0 and y >= 0) or (x < 0 and y < 0):
return _add(x, y)
else:
return __add(x, y)
def _add(x, y):
if y == 0:
return x
else:
return _add((x ^ y), ((x & y) << 1))
def __add(x, y):
if x < 0 < y:
x = _add(~x, 1)
if x > y:
diff = sub(x, y)
else:
diff = sub(y, x)
return diff
elif y < 0 < x:
y = _add(~y, 1)
if y > x:
diff = sub(y, x)
else:
diff = sub(y, x)
return diff
else:
raise ValueError("Invalid Input")
def sub(x, y):
if y > x:
raise ValueError('y must be less than x')
while y > 0:
b = ~x & y
x ^= y
y = b << 1
return x

The most voted answer will not work if the inputs are of opposite sign  It does work in C where integer types are fixedwidth. (At least assuming 2's complement.) I tried it with negative numbers: godbolt.org/z/Lhyh4Y. Perhaps you mean it wouldn't work in Python? May 28 '20 at 20:18
Here is the solution in C++, you can find it on my github here: https://github.com/CrispenGari/AddWithoutIntegerswithoutoperators/blob/master/main.cpp
int add(int a, int b){
while(b!=0){
int sum = a^b; // add without carrying
int carry = (a&b)<<1; // carrying without adding
a= sum;
b= carry;
}
return a;
}
// the function can be writen as follows :
int add(int a, int b){
if(b==0){
return a; // any number plus 0 = that number simple!
}
int sum = a ^ b;// adding without carrying;
int carry = (a & b)<<1; // carry, without adding
return add(sum, carry);
}
This can be done using Half Adder.
Half Adder is method to find sum of numbers with single bit.
A B SUM CARRY A & B A ^ B
0 0 0 0 0 0
0 1 1 0 0 1
1 0 1 0 0 1
1 1 0 1 0 0
We can observe here that SUM = A ^ B and CARRY = A & B
We know CARRY is always added at 1 left position from where it was
generated.
so now add ( CARRY << 1 ) in SUM, and repeat this process until we get
Carry 0.
int Addition( int a, int b)
{
if(B==0)
return A;
Addition( A ^ B, (A & B) <<1 )
}
let's add 7 (0111) and 3 (0011) answer will be 10 (1010)
 A = 0100 and B = 0110
 A = 0010 and B = 1000
 A = 1010 and B = 0000 final answer is A.
Python codes: (1)
add = lambda a,b : (a)(b)
use lambda function with '' operator
(2)
add= lambda a,b : len(list(map(lambda x:x,(i for i in range(a,b)))))