【leetcode74】Sum of Two Integers(不用+,-求两数之和)

题目描述:

不用+,-求两个数的和

原文描述:

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.

方法一:用位运算模拟加法

思路1:

  • 异或又被称其为“模2加法“
  • 设置变量recipe模拟进位数字,模拟加法的实现过程

代码:

public class Solution {
    public int getSum(int a, int b) {
         int r = 0, c = 0, recipe = 1;
        while ((a | b | c) != 0) {
            if (((a ^ b ^ c) & 1) != 0)
                r |= recipe;
            recipe <<= 1;
            c = (a & b | b & c | a & c) & 1;
            a >>>= 1;
            b >>>= 1;
        }
        return r;
    }
}

方法二:异或求值

思路二:

  • a^b,求得结果
  • a&b,求得进位
  • 相加

代码:

public class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int c = a & b; //carry
            a ^= b; //add 
            b = c << 1;
        }
        return a;
    }
}

更多的leetcode的经典算法,查看我的leetcode专栏,链接如下:

leetcode专栏

我的微信二维码如下,欢迎交流讨论

这里写图片描述

欢迎关注《IT面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!

微信订阅号二维码如下:

这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值