A + B 问题

来源:互联网 发布:川大网络教育 编辑:程序博客网 时间:2024/06/14 16:28

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。【位运算】

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 (b == 0){
            return a;
        }
        return aplusb(a ^ b , (a & b) << 1);
        //用位运算代替加法时 ^表示相加 &表示进位 
        //二者相加时进位要左移一位,因为进位是跟上一位相加的
        //!!!!!!!!注意不要忘记后面的括号!
    }
};

0 0
原创粉丝点击