[LeetCode] C++: Simple Questions-Bit Operation 371. Sum of Two Integers

371. Sum of Two Integers

Easy difficulty 364

Without the use of operators  + and  - two integers, calculation a , b sum.

Example 1:

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

Example 2:

Input: a = -2, b = 3
 Output: 1
  •  a ^ b to get the result of adding two numbers without carry

  • (A & b) << 1 Get the carry generated by adding two numbers

class Solution {
public:
    int getSum(int a, int b) {
        if(!(a & b)){
            return a^b;
        }
        return getSum(a^b, ((unsigned int)(a & b)) << 1);
    }
};

 

class Solution {
public:
    int getSum(int a, int b) {
        return a+=b;
    }
};

 

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113772553
Recommended