刷题-Leetcode-371. 两整数之和

371. 两整数之和

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-two-integers/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

在这里插入图片描述

题目分析

以32位机为例,int 分为无符号 unsigned 和有符号 signed 两种类型,默认为signed。
使用与&运算 向左移动一位,求出进位。再与a^b相加。
https://www.cnblogs.com/lawliet12/p/10800905.html

在-1,1的测试用例中,出现报错:
在这里插入图片描述
参考链接:https://blog.csdn.net/EngineerHe/article/details/103361015
原因:负数左移。如果左移的数的最高位是符号位,有的编译器会报错。

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

猜你喜欢

转载自blog.csdn.net/qq_42771487/article/details/117932203
今日推荐