371. Sum of Two Integers

1. Description

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

2. Example

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

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

3. Solutions

My Accepted Solution

Time complexity: O(b)
Space complexity: O(1)

// so stupid

class Solution
{
public:
    // int getSum(int a, int b)
    int getSum(int a, int b)
    {
        vector<int> twoNumbers{a, b};

        return accumulate(twoNumbers.begin(), twoNumbers.end(), 0);
    }
};

3.1 Bit Manipulation

Time complexity: O(b)
Space complexity: O(1)

class Solution
{
public:
    // int getSum(int a, int b)
    int getSum(int a, int b)
    {
        while(b)
        {
            int carry = (a & b & 0x7fffffff) << 1; // & will get the sum's carry
            a = a ^ b; // & will get the sum without carry
            b = carry;
        }
        
        return a;
    }
};
comments powered by Disqus