美文网首页Leetcode
Leetcode 371. Sum of Two Integer

Leetcode 371. Sum of Two Integer

作者: SnailTyan | 来源:发表于2018-09-05 18:20 被阅读2次

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

    1. Description

    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/

    相关文章

      网友评论

        本文标题:Leetcode 371. Sum of Two Integer

        本文链接:https://www.haomeiwen.com/subject/vqhzwftx.html