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

Score After Flipping Matrix Problem

LeetCode 861. You are given an m x n binary...

Chalkboard Xor Game Problem

LeetCode 810. You are given an array of integers nums...

Bitwise ORs Of Subarrays Problem

LeetCode 898. We have an array arr of non-negative integers....

Binary Gap Problem

LeetCode 868. Given a positive integer n, find and return...

K-Th Symbol In Grammar Problem

LeetCode 779. We build a table of n rows (1-indexed)....