题目 “A + B Problem”
Example:
Given a=1 and b=2 return 3.
Challenge:
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
Clarification:
Are a and b both 32-bit integers?
Yes.
Can I use bit operation?
Sure you can.
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.
话不多说,直接上代码
// 直接从lintcode上拷贝的代码
class Solution {
public:
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here
int a_=0,b_=0;
while(b!=0)
{
a_=a^b;
b_=(a&b)<<1;
a=a_;
b=b_;
}
return a;
}
};
代码解读
- 创建两个中间变量a_,b_
- 将待做加法运算的a,b进行按位异或,结果存入a_
- 将a,b按位与,并左移一位,结果存入b_
- a=a_
- b=b_
- 直到b的值等于0
这是我第一次写博客,过程有点简单,写的不好的地方,还请各位勿喷。