Leetcode 371. Sum of Two Integers

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

《Leetcode 371. Sum of Two Integers》 Sum of Two Integers

2. Solution

  • Version 1
class Solution {
public:
    int getSum(int a, int b) {
        int sum = 0;
        int carry = 0;
        while(b)
        {
            sum = a ^ b; 
            carry = a & b;
            a = sum;
            b = carry << 1;
        }
        return sum;;
    }
};
  • Version 2
class Solution {
public:
    int getSum(int a, int b) {
        return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
    }
};

Reference

  1. https://leetcode.com/problems/sum-of-two-integers/description/
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/4f78c54fe414
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞