天天看点

[LeetCode] 371、两整数之和

题目描述

不使用运算符

+

-

,计算两整数

a

b

之和。

示例:

输入: a = 1, b = 2
输出: 3
           

解题思路

原题。(书上没考虑溢出问题,边界值有坑:

runtime error: left shift of negative value -2147483648

  • python“作弊”法:

    return sum([a, b])

参考代码

class Solution {
public:
    int getSum(int a, int b) {
        int temp, carry;
        do{
            temp = a ^ b;
            carry = (unsigned int)(a & b) << 1;   // (unsigned int)关键!!!
            a = temp;
            b = carry;
        }while(carry != 0);
        
        return temp;
    }
    
};