Leetcode-371-Sum of Two Intergers

题目要求: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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值