LintCode真題之A+B問題

問題描述:

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。