371. Sum of Two Integers

Calculate the sum of two integersaandb, but you arenot allowedto use the operator+and-.

Example 1:

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

Example 2:

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

Thoughts: (from Bit Manipulation Summary)

  1. ^ tricks: Use ^to remove even exactly same numbers and save the odd, or save the distinct bits and remove the same. Sum of Two Integers Use^and&to add two integers

Code

class Solution {
public:
    int getSum(int a, int b) {
        return b == 0? a: getSum(a^b, (a&b) << 1);
    }
};

results matching ""

    No results matching ""