How to add two numbers without the operators +,-,*,/ ?

Recently I found an interview question: How to add two numbers without the operators +,-,*,/. During in an interview, this question is just horrible. From my point of view it doesn’t matter if an interviewee knows the answer or not. Anyway, here is the answer: Use bitwise operations.

Theory first, without code

A binary add is simple. First of all the numbers (this example adds 10 and 10) have to converted into a binary number or base-2 number. You can use an online converter or you can do it on your own.

10 : 2 = 5 remains 0
5 : 2 = 2 remains 1
2 : 2 = 1 remains 0
1 : 2 = 0 remains 1

1010 = 10102

The addition of two numbers within the base-2 numeral system is similar to the base-10 addition. The rules are 0 + 0 = 0, 1 + 0 = 1, 0 + 1 = 1 and 1 + 1 = 10 (with a carry). Go from the right to the left.

1010
+ 1010
= 10100

If you’re not so familiar with the carry-thing, read the following explanation: As you can the see the result of 1 + 1 is 10, so write down the zero and carry the 1 to the next row. This row is now 0 + 0 + 1 = 1 and so on.

How can I do this with C# code?

The method to add two numbers with bitwise operations has only a few lines. Integer variables work directly with the operators.

private int Add(int x, int y)
{
	int a, b;
	do
	{
		a = x & y;
		b = x ^ y;
				
		x = a << 1;
		y = b;
	} while (a != 0);
			
	return b;
}

To understand how this methods works, we simply write down each loop within the while.

First loop:

a = 1010 & 1010 = 1010 (Remember &: 1&1=1, 1&0=0, 0&0=0, 0&1=0)
b = 1010 ^ 1010 = 0 (Remember ^: 1^1 = 0, 1^0=1, 0^0=0, 0^1=1)
x = 1010 << 1 = 10100 (Remember: << 1 shifts one digit to the left)
y = b = 0

Second loop:

a = 10100 & 0 = 0 (Remember &: 1&1=1, 1&0=0, 0&0=0, 0&1=0)
b = 10100 ^ 0 = 10100 (Remember ^: 1^1 = 0, 1^0=1, 0^0=0, 0^1=1)
x = 10100 << 1 = 101000 (Remember: << 1 shifts one digit to the left)
y = b = 0

We have only two loops, because the condition (a != 0) is false. The result is 101002 and 2010

It is simple, isn’t it?

Advertisements
This entry was posted in C#, Development and tagged , , . Bookmark the permalink.

One Response to How to add two numbers without the operators +,-,*,/ ?

  1. coder says:

    Smart! Good to know how to add two number together without plus operator.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s