Skip to content

Latest commit

 

History

History
81 lines (69 loc) · 2.13 KB

README.md

File metadata and controls

81 lines (69 loc) · 2.13 KB

Given two integers a and b, return the sum of the two integers without using the operators + and -.

 

Example 1:

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

Example 2:

Input: a = 2, b = 3
Output: 5

 

Constraints:

  • -1000 <= a, b <= 1000

Companies:
Facebook

Related Topics:
Bit Manipulation

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/sum-of-two-integers/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int getSum(int a, int b) {
        int carry = 0, ans = 0;
        for (int i = 0; i < 32; ++i) {
            int x = (a >> i & 1), y = (b >> i & 1);
            if (carry) {
                if (x == y) {
                    ans |= 1 << i;
                    if (!x & !y) carry = 0;
                }
            } else {
                if (x != y) ans |= 1 << i;
                if (x & y) carry = 1;
            }
        }
        return ans;
    }
};

Solution 2.

  1. Get carry = (a & b) << 1, i.e. the bits that are 1s both in a and b are picked and shifted left by 1.
  2. As the 11 case is handled, the rest 10, 01, 00 cases can be get using a ^ b.
  3. Now the problem becomes calculating the sum of (a & b) << 1 and a ^ b.
  4. Go back to step 1 until there is no more carry.
// OJ: https://leetcode.com/problems/sum-of-two-integers/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int getSum(int a, int b) {
        while (b) {
            int carry = (a & b) << 1;
            a ^= b;
            b = carry;
        }
        return a;
    }
};