Description:
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.
感觉自己智商不够用了
一开始觉得应该是用加法器的原理来实现,然而自己写的那个写了40行然后还错误一堆,人家写的就两行
int getSum(int a, int b) {
if(!a)
return b;
else
return getSum((a&b)<<1,a^b);
}
就这样
就是要考虑两个部分
1.进位
0+0→不进位
0+1→不进位
1+0→不进位
1+1→进位,即相当于是10,将10加到不考虑进位的计算结果上,即可得到整个的计算结果,而可以用位运算的与操作和向左的移位操作即可模拟上述的是否进位:
0&0=0 (0&0)<<1=0
0&1=0 (0&1)<<1=0
1&0=0 (1&0)<<1=0
1&1=1 (1&1)<<1=10
2.不考虑进位的计算结果。
以一位二进制数来表示:
1^1=0
1^0=1
0^1=1
0^0=0
就是a^b
一共计算两次,第一次是两个数相加产生进位, 产生新的原来的位置的数据,然后将这两个产生的数据再相加。
参考了http://zhidao.baidu.com/question/404020081.html (头一次在百度知道看到这么高质量的回答)
======下面是不怕丢人的分割线=====
自己写的傻逼代码
//simulate an adder, i,j is the digit of two number, k is the flag of carry
// int i,j,k;
// k=0;
// int answer = 0;
// //calculate the loop
// int loop = 1;
// while(true){
// //get the last digit of a
// if((a/2) == (int)(a/2)){
// a = (int)a/2;
// i = 0;
// } else if((a/2)!=0){
// a = (int)a/2;
// i = 1;
// }
// //get the last digit of b
// if((b/2) == (int)(b/2)){
// b = (int)b/2;
// j = 0;
// } else if((b/2)!=0){
// b = (int)b/2;
// j = 1;
// }
// //add the two digit, put the answer to variable “answer”
// answer += (i^j)*(std::pow(2,loop));
// //add the vaule of carry to “answer”
// answer += k*(std::pow(2,loop));
// if(i&&j)
// k = 1;
// else
// k = 0;
// loop++;
// if(bool(a)||bool(b)||bool(k)) break;
// }
// return answer;