标签:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
不用加减法计算两个整数的和。这道题其实是考察一些基本的布尔代数知识。我们知道,二进制表示时:
0 + 0 = 00
1 + 0 = 01
0 + 1 = 01
1 + 1 = 10
所以,两个二进制整数
所以有如下关系:
如果
设
这个过程很容易写成递归程序:
int getSum(int a, int b)
{
if(a == 0) return b;
int x = a ^ b;
int c = (a & b) << 1;
return getSum(c, x);
}
当然,也可以用也可以不用递归:
int getSum2(int a, int b)
{
while(a)
{
int x = a ^ b;
a = (a & b) << 1;
b = x;
}
return b;
}
LeetCode 第 371 题 (Sum of Two Integers)
标签:
原文地址:http://blog.csdn.net/liyuanbhu/article/details/51803974