Add Numbers without using Plus operator – Interview Question
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?
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:
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.
This can be computed using the XOR operator.
For carry over, let’s see how it looks like:
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.
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 😊