题目要求:Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
求两个整型数的和,但是不可使用+和-运算符
例:Given a = 1 and b = 2, return 3.
解题思路:1.既然不能使用“+”“-”运算符,就考虑位运算
2.例如13+1,13(1101)1(0001),对两个数按位求异或,可得1100,易知:1和0求得为1,0和0求得为0,都没问题,问题在于1和1求得为0,应该是将其向左进1,所以解决的办法就是求得同为1的位,即求按位求与可得,并且左移以为,在将其加到结果中即可求得
代码如下:
<script type="text/javascript">
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
while(a != 0){
var remove = (a & b) << 1;
b = a ^ b;
a = remove;
}
alert(b);
};
getSum(11,1);
</script>