Write a function that add two numbers A and B. You should not use +
or any arithmetic operators.
Notice
There is no need to read data from standard input stream. Both parameters are given in function aplusb
, you job is to calculate the sum and return it.
Are a and b both 32-bit
integers?
- Yes.
Can I use bit operation?
- Sure you can.
Given a=1
and b=2
return 3
此题考查的是位计算(亦或运算)
思路:
考虑一个普通的加法计算:5+17=22
在十进制加法中可以分为如下3步进行:
1. 忽略进位,只做对应各位数字相加,得到12(个位上5+7=12,忽略进位,结果2);
2. 记录进位,上一步计算中只有个位数字相加有进位1,进位值为10;
3. 按照第1步中的方法将进位值与第1步结果相加,得到最终结果22。
下面考虑二进制数的情况(5=101,17=10001):
仍然分3步:
1. 忽略进位,对应各位数字相加,得到10100;
2. 记录进位,本例中只有最后一位相加时产生进位1,进位值为10(二进制);
3. 按照第1步中的方法将进位值与第1步结果相加,得到最终结果10110,正好是十进制数22的二进制表示。
接下来把上述二进制加法3步计算法用位运算替换:
第1步(忽略进位):0+0=0,0+1=1,1+0=0,1+1=0,典型的异或运算。
第2步:很明显,只有1+1会向前产生进位1,相对于这一数位的进位值为10,而10=(1&1)<<1。
第3步:将第1步和第2步得到的结果相加,其实又是在重复这2步,直到不再产生进位为止。
代码如下:
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
int carry = 0;
while (b)
{
carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};