371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

計算兩個整數a,b之和,不能使用操作符+或-。

Example:
Given a = 1 and b = 2, return 3.

下面是我的實現
int getSum(int a, int b) {
    int sum,carry=0;
    sum=a^b;
    carry=(a&b)<<1;
    if(carry==0)
        return sum;
    else
    return getSum(sum,carry);
}

sum是兩數異或的結果,carry是進位結果,不斷遞歸計算,當進位爲0的時候返回sum值。

提交結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章