当前位置:首页 > 未命名 > 正文内容

【解题报告】【lintcode1】A + B Problem

u3blog8年前 (2016-05-17)未命名223

题意

不适用任何数学运算实现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.
        while(b != 0){
            int carry = a&b;
            a = a^b;
            b = carry<<1;
        }
        return a;
    }
};

扫描二维码推送至手机访问。

版权声明:本文由u3blog发布,如需转载请注明出处。

本文链接:https://u3blog.xyz/?id=414

分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。