先了解异或和与运算:
0和1的异或运算如下:0^0 = 0, 1^0 = 1, 0^1 = 1,1^1 = 0
再看看与运算:0&0=0; 0&1=0; 1&0=0; 1&1=1;
那么加法运算可以这样实现:
1)先不考虑进位,按位计算各位累加(用异或实现),得到a;
2)然后计算进位,并将进位的值左移,得到值b。若b为0,则a就是加法运算的结果;若b不为0,则a+b即得结果(递归调用这个过程)。
function bitAdd(a,b){
if(b==0){
return a;
}
var sum = a^b;
var carry = (a&b)<<1;
return bitAdd(sum,carry);
}
bitAdd(5,7)
12
参考文章:
https://blog.csdn.net/g6U8W7p06dCO99fQ3/article/details/79227169
https://www.cnblogs.com/houjun/p/4908725.html
https://blog.csdn.net/u013793732/article/details/79506927
https://www.cnblogs.com/newpanderking/p/3925056.html
https://brokendreams.iteye.com/blog/2084088
https://blog.csdn.net/qq_38148754/article/details/82315531