Sum Of Two Integers Problem


Description

LeetCode Problem 371.

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

Example 1:

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

Example 2:

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

Constraints:

  • -1000 <= a, b <= 1000


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    int getSum(int a, int b) {
        int sum = 0, c = 0;
        int p, q, n = 1, s, i = 1;
        bool neg;
        if (a < 0 && b < 0)
            neg = true;
        else if ((a < 0 && -(unsigned int)a > b) || (b < 0 && -(unsigned int)b > a))
            neg = true;
        else
            neg = false;
        
        while (i < 32) {
            p = a & 1, q = b & 1;
            s = p ^ q ^ c;
            c = (p & q) || (p & c) || (q & c);
            sum = (s == 1) ? (sum | n) : (sum);
            n = n << 1, a = a >> 1, b = b >> 1;
            i ++;
        }
        
        if (neg && sum != 0)
            sum -= 2147483648;

        return sum;
    }
};




Related Posts

Bulb Switcher II Problem

LeetCode 672. There is a room with n bulbs labeled...

Binary Number With Alternating Bits Problem

LeetCode 693. Given a positive integer, check whether it has...

Total Hamming Distance Problem

LeetCode 477. The Hamming distance between two integers is the...

Number Complement Problem

LeetCode 476. The complement of an integer is the integer...

Hamming Distance Problem

LeetCode 461. The Hamming distance between two integers is the...

Convert A Number To Hexadecimal Problem

LeetCode 405. Given an integer num, return a string representing...