371. Sum of Two Integers
来源:互联网 发布:哈佛东亚研究中心 知乎 编辑:程序博客网 时间:2024/05/22 03:42
题目:两个整数的和
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.
题意:
计算两个整数a和b的和,但是不允许使用+、-计算操作符。
思路:转载:http://www.cnblogs.com/grandyang/p/5451942.html
位操作Bit Manipulation,我们在做加法运算的时候,每位相加之后可能会有进位Carry产生,然后在下一位计算时需要加上进位一起运算,那么我们能不能将两部分拆开呢,我们来看一个例子759+674
1. 如果我们不考虑进位,可以得到323
2. 如果我们只考虑进位,可以得到1110
3. 我们把上面两个数字假期323+1110=1433就是最终结果了
然后我们进一步分析,如果得到上面的第一第二种情况,我们在二进制下来看,不考虑进位的加,0+0=1, 0+1=1, 1+0=1, 1+1=0,这就是异或的运算规则,如果只考虑进位的加0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是与的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,我们直接返回第一步的结果。
代码:C++版:0ms
class Solution {public: int getSum(int a, int b) { if (b == 0) return a; int sum = a ^ b; int carry = (a & b)<<1; return getSum(sum, carry); }};不使用递归版本:C++版:0ms
class Solution {public: int getSum(int a, int b) { while (a) { int x = a ^ b; a = (a & b)<<1; b = x; } return b; }};
0 0
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 进程线程总是无法理解,小记一下
- Gedit中文乱码
- Volist判断输出的最后一个元素
- 使用Handler需要谨慎,否则可能造成内存泄漏
- Oracle 11g R2 DBA 操作指南(5)
- 371. Sum of Two Integers
- 系统硬件概述学习
- POJ 2528 Mayor's posters(线段树 + 离散化--静态实现)
- 孟夏情
- Docker数据管理:data container
- 使用Redis的Pub/Sub来实现类似于JMS的消息持久化
- Java 三种线性排序之计数排序
- 第1章 实现启动
- Spring中IOC的一个简单入门实例(搬运工)