[LeetCode]371. Sum of Two Integers

不用加号做加法

Posted by JinFei on September 27, 2021

题目描述

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

Example1:

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

解题思路

  • 普通做加法的过程
  • 第一步,先算出 不进位的加法 用异或运算 sum = a ^ b (相同为0,相异为1)
  • 算出相应进位 通过 与运算,相同为1,相异为0,然后记得左移一位
  • 这只是一次过程 继续累加
class Solution {
public:
    int getSum(int a, int b) {
        int sum = a;
        while(b != 0){
            sum = a ^ b;    // 不进位的进行加
            b = ((unsigned int)(a & b)) << 1;   // 算出进位
            a = sum;        // 进行循环
        }
        return sum;
    }
};