Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
/**
* 不用 + -实现两个数相加
* 两个数转换为二进制,
* 1.各位数不进位,即异或运算
* 2.记下进位,结果符合两个数的与运算结果然后向左移动一位
* 3.把前两步骤的结果相加,相加步骤仍然是重复前两步骤。直到不产生进位值。
* @param num1
* @param num2
* @return
*/
public int Add(int num1, int num2) {
int sum;
int carry;
do {
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
} while (num2 != 0);
return num1;
}