Add Numbers without using Plus operator – Interview Question

Add Numbers without using Plus operator – Interview Question

May 23, 2019 Uncategorized 0


You have to write an algorithm that adds two numbers but you are not allowed to use the plus operator.

The first thought that comes to my mind is using binary numbers. We need to think how we can do addition using binary numbers and what all are the steps you follow when you actually do an addition.

Take two numbers: Let’s say 29 and 33.
If you have to add them manually, what do you do?

29
+33

You sum the digits at the unit place. If there is a carry, you carry it over. Then you sum the digits at the tens place and again you carry the carry over and so on.
If this were binary, it would look something like this:

00011101
+00100001
___________
00111110

There are 2 components here: Actually summing up the numbers and the other is to carry over.
If you were to do them separately what would happen?
Let’s sum up the numbers without carry over.

00011101
+ 00100001
____________
00111100
This can be computed using the XOR operator.

For carry over, let’s see how it looks like:
00011101
+ 00100001
____________
00000010

This can be computed by AND of all the bits and then left shift by one.
And if you were to add these two numbers i.e. the resultant of sum without carry and the resultant of only carry, you will get the required sum.
00111100
+ 00000010
____________
00111110

So something like this:
Int c = a ^ b;
Int d = (a & b) << 1
Return c + d;

However, as you must have noticed we are still using the addition operator in the last line.
Since we don’t want to use addition operator, we can recursively call our code to keep adding until the second number is zero. The base condition will be if second number is zero, return the first number.

Here is the Github link to the working solution. I will recommend you to try it on your own before looking at the solution.

Hope you like this interview question. I will be adding more such questions to my YouTube channel. So please subscribe.
Until next time, happy coding 😊