[leetcode] 371. Sum of Two Integers

网友投稿 284 2022-11-14

[leetcode] 371. Sum of Two Integers

Description

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

Example 1:

Input:

a = 1, b = 2

Output:

3

Example 2:

Input:

a = -2, b = 3

Output: 1

分析

题目的意思是:给定a和b,求出a+b但是不能用+,-运算符。

用与或非运算,这是个递归。例如: 759+674

如果我们不考虑进位,可以得到 323如果我们只考虑进位,可以得到 1110我们把上面两个数字加起来 323+1110=1433 就是最终结果了

在二进制下来看,不考虑进位的加,0+0=0,0+1=1, 1+0=1,1+1=0,这就是异或的运算规则,如果只考虑进位的加 0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是’与’的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,直接返回第一步的结果。

代码

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

参考文献

​​[LeetCode] Sum of Two Integers 两数之和​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot读取yml文件中配置数组的2种方法
下一篇:串行端口在工业单板计算机中的应用
相关文章

 发表评论

暂时没有评论,来抢沙发吧~