From: http://sllovewsy149.blog.163.com/blog/static/108734178201245114626125/
Reference: http://blog.csdn.net/morewindows/article/details/8710737
Q: Write an algorithm to add two numbers, but do not use addition (+) or other arithmetic operations.
A: First, consider how we add two decimal numbers.
759 + 674, get 323 without considering carry.
If we only consider carrying, we get 1110.
So we get 759 + 674 = 323 + 1110 = 1433
What does the computer do with the binary number?
Use an exclusive or (^) without considering carry)
If we only consider the carry, we use (&) and shift left (<) at the same time.
Use recursion until the carry value is 0. Then the sum of the two numbers is obtained.
The following is the Java code:
1: public int addNoArithm(int a, int b) {
2: if (b == 0) {
3: return a;
4: }
5: int sum = a ^ b;
6: int carry = (a & b) << 1;
7: return addNoArithm(sum, carry);
8: }
PS: we do not need to use arithmetic operations to obtain the sum of two numbers. We should first think of bitwise operations, because it seems that we have no other choice.