問題描述:
給出兩個(gè)整數(shù)a和b, 求他們的和, 但不能使用 + 等數(shù)學(xué)運(yùn)算符。
注意事項(xiàng)
你不需要從輸入流讀入數(shù)據(jù),只需要根據(jù)aplusb的兩個(gè)參數(shù)a和b,計(jì)算他們的和并返回就行。
說明
a和b都是 32位 整數(shù)么?
是的
我可以使用位運(yùn)算符么?
當(dāng)然可以
code1:(copy來自網(wǎng)絡(luò)大神)
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;
}
};