您的位置:首页 > 其它

A + B 问题

2016-05-31 18:32 405 查看
给出两个整数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);

        //用位运算代替加法时 ^表示相加 &表示进位 

        //二者相加时进位要左移一位,因为进位是跟上一位相加的

        //!!!!!!!!注意不要忘记后面的括号!

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: