LeetCode-371~Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -
Example:Given a = 1 and b = 2, return 3.
不使用+-等运算符计算a和b的和

算法分析

假设a与b相加

  • 不考虑进位:a^b为a与b中数字相加的和
  • 考虑进位:a&b<<1为a与b相加应有的进位
  • a+b可以转换为a^b + a&b<<1
  • a&b为0时,a^b为要求的和

Java代码

public class Solution {
    public int getSum(int a, int b) {
        int x = a & b;//相加后的进位
        int y = a ^ b;//相加后的数字和
        
        if (x == 0) return y;
        else return getSum(x<<1, y);
    }
}

参考

LeetCode
oschina

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容