LeetCode:371. Sum of Two Integers Sum of Two Integers两整数之和(C语言)

左手的ㄟ右手 2022-12-27 01:47 224阅读 0赞

题目描述:
不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。

示例 1:

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

示例 2:

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

通过次数41,261
提交次数72,634

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

  1. int getSum(int a, int b){
  2. int sum = a ^ b;
  3. int carry = (unsigned int)(a & b) << 1;
  4. if(0 == carry){
  5. return sum;
  6. }
  7. else{
  8. return getSum(sum,carry);
  9. }
  10. }

运行结果:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Sum of Two Integers

    思路:在不使用运算符求和的问题中,最容易想到的一种方法是借助与、异或和移位操作符。与和移位操作符配合使用可以找到进位,异或操作符能够找到非进位,两者相加得到Sum,由于不允许使