A + B problem

Description:

計算A + B,但是不能用加法運算符。

 

 

解決思路:用位運算符。

 

 

Code:

public class Solution {
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b 
     */
    public int aplusb(int a, int b) {
        // write your code here

        //循環
        // while(b != 0){
        //     int _a = a ^ b;
        //     int _b = (a & b) << 1;
        //     a = _a;
        //     b = _b;
        // }
        // return a;

        //遞歸
        int _a = a ^ b;
        int _b = (a & b) << 1;
        a = _a;
        b = _b;
        if (b == 0){
            return a;
        } 
        return aplusb(a,b);
        
    }
}

 

 

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