首页 > 其他 > 详细

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

时间:2016-07-30 16:48:45      阅读:170      评论:0      收藏:0      [点我收藏+]

题目描述:

不用+,-求两个数的和

原文描述:

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面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!

微信订阅号二维码如下:

技术分享

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

原文:http://blog.csdn.net/lpjishu/article/details/52073527

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!