371. Sum of Two Integers

https://leetcode.com/problems/sum-of-two-integers/

Problem

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

Example 1:

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

Example 2:

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

Solution

class Solution {
public:
    int getSum(unsigned int a, unsigned int b) {
        while (b != 0) {
            unsigned int temp = a;
            a = a ^ b;
            b = (temp & b) << 1;
        }
        return a;
    }
};
  • #bitwise

Last updated

Was this helpful?