371. Sum of Two Integers

Problem

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example

Input: a = 1, b = 2
Output: 3
Input: a = -2, b = 3
Output: 1

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int getSum(int a, int b) {
        if(!b)
            return a;
        int Xor = a ^ b;
        int And = (a & b) << 1;
        return getSum(Xor,And);
    }
};

Result

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

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 设计模式分类 创建型模式->5种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式 结构型模式->7种:...
    宇宙高哥阅读 452评论 0 0
  • 目 录下一章 “不好意思,可以停一下吗?”Henry礼貌性的插了一句话。 嗝。 少年愣神了一下,识时务者不为林俊杰...
    一枚少年阅读 666评论 2 49