A + B Problem

A + B Problem

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

Example

Given a=1 and b=2 return 3.

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
//两个数异或:相当于每一位相加,而不考虑进位;
//如果两个数的二进制每一位都不一样 比如01和10,那么x=11;
//那么如果有进位呢?比如01和01,那么应该是满2进1,如何做(a&b)<<1=10
//那么a&0等于a本身,那么当b=0时,a就是两个数的和
//两个数相与,并左移一位:相当于求得进位;
int x = a^b;
int y = a&b;
if(y==0){
return x;
}else{
return aplusb(x,y<<1);
}
}
}