leetcode submission/20161012(sum of two integers)
来源:互联网 发布:淘宝订机票 编辑:程序博客网 时间:2024/05/01 04:03
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.
解题思路还是和之前算过的single number一样,利用进位原则:
1、输入 a,b
2、按照位把ab相加,不考虑进位,结果是 a xor b,即1+1 =0 0+0 = 0 1+0=1
3、计算ab的进位的话,只有二者同为1才进位,因此进位可以标示为 (a and b) << 1 ,注意因为是进位,所以需要向左移动1位
4、于是a+b可以看成 (a xor b)+ ((a and b) << 1),这时候如果 (a and b) << 1 不为0,就递归调用,因为(a xor b)+ ((a and b) << 1) 也有可能进位,所以我们需要不断的处理进位。
public class solution {
public int getSum(int a, int b) {
int xor = a^b;
int and = a&b<<1;
if (and != 0)
return getSum(xor, and);
return xor;
}
}
或者就一行
class Solution {
public:
int getSum(int a, int b) {
return (b == 0) ? a : getSum(a^b, (a&b)<<1);
}
};
reference:http://www.cnblogs.com/grandyang/p/5631814.html
- leetcode submission/20161012(sum of two integers)
- 【Leetcode】Sum of Two Integers
- leetcode Sum of Two Integers
- LeetCode---Sum of Two Integers
- LeetCode:Sum of Two Integers
- LeetCode:Sum of Two Integers
- LeetCode Sum of Two Integers
- Leetcode Sum of Two Integers
- #leetcode#Sum of Two Integers
- Leetcode-Sum of Two Integers
- leetcode--sum of two integers
- [Leetcode] Sum of Two Integers
- LeetCode|Sum of Two Integers
- [Leetcode] Sum of Two Integers
- LEETCODE--Sum of Two Integers
- LeetCode:Sum of Two Integers
- LeetCode Sum of Two Integers
- leetcode[Sum of Two Integers]
- WEB前端人员须知的常见浏览器兼容问题及解决技巧
- mpstat命令
- 自己的学习笔记 - SQL
- ubuntu16.04下安装TensorFlow(GPU加速)----详细图文教程
- 文件访问控制权限
- leetcode submission/20161012(sum of two integers)
- FPGA 驱动舵机
- SSM框架---容器创建注入对象失败异常之个人原因分析小记
- wmsys.wm_concat
- 【题】【数学(欧拉函数)】NKOJ3801 分解质因数
- Price
- 操作系统进程调度算法图解(FCFS、轮转、SPN、SRT、HRRN、反馈)
- HDU 5829 16多校08 Rikka with Subset (NTT)
- 洛谷 P1080 国王游戏