Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

这道题是 CareerCup 上的一道原题,可参见博主之前的博客 18.1 Add Two Numbers。这里让实现两数相加,但是不能用加号或者其他什么数学运算符号,那么只能回归计算机运算的本质,位操作 Bit Manipulation,在做加法运算的时候,每位相加之后可能会有进位 Carry 产生,然后在下一位计算时需要加上进位一起运算,那么能不能将两部分拆开呢,来看一个例子 759+674

1. 如果不考虑进位,可以得到 323

2. 如果只考虑进位,可以得到 1110

3. 把上面两个数字假期 323+1110=1433 就是最终结果了

然后进一步分析,如果得到上面的第一第二种情况,在二进制下来看,不考虑进位的加,0+0=0,0+1=1, 1+0=1,1+1=0,这就是异或的运算规则,如果只考虑进位的加 0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是'与'的运算,而第三步在将两者相加时,再递归调用这个算法,终止条件是当进位为0时,直接返回第一步的结果。一切都是如此的美好,突然有一天,博主的所有方法都无法通过 OJ 了,不知为何,原因不明。在热心网友 GGGGITFK 的提示下,终于知道了错误的原因:

runtime error: left shift of negative value -2147483648,对INT_MIN左移位。

就是 LeetCode 自己的编译器比较 strict,不能对负数进行左移,就是说最高位符号位必须要为0,才能左移(此处应有尼克杨问号脸?!),好吧,你赢了。那么在a和b相 '与' 之后,再'与'上一个最高位为0,其余位都为1的数 0x7fffffff,这样可以强制将最高位清零,然后再进行左移,终于,世界清静了,参见代码如下:

解法一:

class Solution {
public:
int getSum(int a, int b) {
if (b == ) return a;
int sum = a ^ b;
int carry = (a & b & 0x7fffffff) << ;
return getSum(sum, carry);
}
};

上面的解法可以精简到一行,哈哈,叼不叼?

解法二:

class Solution {
public:
int getSum(int a, int b) {
return b == ? a : getSum(a ^ b, (a & b & 0x7fffffff) << );
}
};

也可以写成迭代的样子,思路都是一样的~

解法三:

class Solution {
public:
int getSum(int a, int b) {
while (b) {
int carry = (a & b & 0x7fffffff) << ;
a = a ^ b;
b = carry;
}
return a;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/371

类似题目:

Add Two Numbers

参考资料:

https://leetcode.com/problems/sum-of-two-integers/

https://leetcode.com/problems/sum-of-two-integers/discuss/84290/Java-simple-easy-understand-solution-with-explanation

https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Sum of Two Integers 两数之和的更多相关文章

  1. Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)

    Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted) 给定一个已按照升序排列 的有序数组,找到两个数使得它们 ...

  2. LeetCode(1): 两数之和

    本内容为LeetCode第一道题目:两数之和 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 19:57:18 201 ...

  3. leetcode题库练习_两数之和

    题目:两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能 ...

  4. [LeetCode] Sum of Square Numbers 平方数之和

    Given a non-negative integer c, your task is to decide whether there're two integers a and b such th ...

  5. [LeetCode] 29. Divide Two Integers 两数相除

    Given two integers dividend and divisor, divide two integers without using multiplication, division ...

  6. LeetCode 刷题笔记 1. 两数之和(Two Sum)

    tag: 栈(stack) 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案. ...

  7. LeetCode每天一题之两数之和

    这个LeetCode刷题系列的博客权当是为自己记一下笔记吧.博客系列会从LeetCode的第一题开始刷,同时会从零开始学习[因为我就是零/(ㄒoㄒ)/~~].同时,如果有写错的地方,希望大佬们在评论区 ...

  8. LeetCode(1):两数之和

    写在前面:基本全部参考大神“Grandyang”的博客,附上网址:http://www.cnblogs.com/grandyang/p/4130379.html 写在这里,是为了做笔记,同时加深理解, ...

  9. 371 Sum of Two Integers 两整数之和

    不使用运算符 + 和-,计算两整数a .b之和.示例:若 a = 1 ,b = 2,返回 3. 详见:https://leetcode.com/problems/sum-of-two-integers ...

随机推荐

  1. 实验:Oracle直接拷贝物理存储文件迁移

    实验目的:Oracle直接拷贝物理文件迁移,生产库有类似施工需求,故在实验环境简单验证一下. 实验环境: A主机:192.168.1.200 Solaris10 + Oracle 11.2.0.1 B ...

  2. Event Sourcing Pattern 事件源模式

    Use an append-only store to record the full series of events that describe actions taken on data in ...

  3. Apache Spark简单介绍、安装及使用

    Apache Spark简介 Apache Spark是一个高速的通用型计算引擎,用来实现分布式的大规模数据的处理任务. 分布式的处理方式可以使以前单台计算机面对大规模数据时处理不了的情况成为可能. ...

  4. ASP.NET MVC View 和 Web API 的基本权限验证

    ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...

  5. web设计页面跳转的方法

    一.asp.net c# 打开新页面或页面跳转 1. 最常用的页面跳转(原窗口被替代):Response.Redirect("newpage.aspx"); 2. 利用url地址打 ...

  6. 使用命令 gradle uploadArchives 的异常: Unable to initialize POM pom-default.xml: Failed to validate POM for project

    在使用:gradle uploadArchives 命令对项目进行上传maven时,常常遇到如下报错: 这时候要仔细的检查一下build.gradle文件中的dependencies内容,很多时候是由 ...

  7. python generator next send

    *******oi********oi********oi 上面  *  符号 代表 一系列的代码, oi 代表 一个 [yield]关键字引出的 [数据交换,称之为 oi ] 在一个有[yield] ...

  8. spring四种依赖注入方式

    一.Set注入 这是最简单的注入方式,假设有一个SpringAction,类中需要实例化一个SpringDao对象,那么就可以定义一个private的SpringDao成员变量,然后创建SpringD ...

  9. Hibernate关联映射 映射文件的配置

    一:多对一单向关联 首先我们必须创建两个实体类 例如:Dept类 public class Dept { private Integer deptNo; private String dName; p ...

  10. 《Web开发过滤Javascript、HTML的方法》

    JavaScript过滤方法: 第一种方案:使用 htmlspecialchars 函数转换特殊字符和使用 nl2br 函数插入一些必要的 <br /> 标签. $comment = &l ...