LeetCode:371. Sum of Two Integers Sum of Two Integers两整数之和(C语言)
题目描述:
不使用运算符 + 和 - ,计算两整数 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
int getSum(int a, int b){
int sum = a ^ b;
int carry = (unsigned int)(a & b) << 1;
if(0 == carry){
return sum;
}
else{
return getSum(sum,carry);
}
}
运行结果:
还没有评论,来说两句吧...