LintCode真题之A+B问题

2018-01-19  本文已影响0人  Sky_Dream369

问题描述:

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

注意事项

你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

说明
a和b都是 32位 整数么?

是的
我可以使用位运算符么?

当然可以

code1:(copy来自网络大神)
class Solution {
/*
* param a: The first integer
* param b: The second integer
* return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
if(a==0) return b;
if(b==0) return a;
int sum,i;
i=a^b;
sum=(a&b)<<1;
return aplusb(sum,i);
}
};

code2:(小白水平---本人)
class Solution {
public:
/*
* @param : An integer
* @param : An integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here
int sum = 0;
vector<int> values = {a, b};
sum = accumulate(values.begin(), values.end(), 0);
return sum;
}
};

上一篇下一篇

猜你喜欢

热点阅读