LintCode真題之A+B問題

問題描述:

給出兩個(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;
}
};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容