[leetcode]371. Sum of Two Integers
来源:互联网 发布:excel表删除重复数据 编辑:程序博客网 时间:2024/06/03 22:48
题目链接: https://leetcode.com/problems/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.
思路: 这里用到了一个半加法的思想, 即两位单独的位相加其结果可以用异或得到, 进位可以用与得到. 然后对于两个数字来说同样可以延伸这个思想.
举个例子: 11+7, 其二进制形式为11: 1011, 7: 01111. 两个位置都为1的地方就需要进位,那么0011=1011&0111 表明了第0位和第1位需要进位。原位置两个数相加的结果为那个位置值的异或即1100=1011^0111, 即两个位置值如果不一样就为1, 一样的话要么两个位置原来值都为0结果也为0, 要么进位, 那么结果依然是0.
2. 接下来就要把进位位和下一位相加, 所以进位值左移一位,即0011变为0110,与原位置异或(即相加)结果为0101=0110^0011.
3. 继续重复上面操作直到进位为0, 可得到最终结果10010, 即18.
代码如下:
class Solution{public: int getSum(int a,int b) { while(b!=0) { int carry=a&b;//进位 a=a^b;//伪相加 b=carry<<1; } return a; }};
0 0
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371.Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of Two Integers
- leetcode.371. Sum of Two Integers
- 371. Sum of Two Integers--LeetCode Record
- LeetCode—371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- Android Studio 添加ButterKnife一件注解
- android 一个用户引导控件
- 2016最新全国省市区sql
- window.onload和$(document).ready()的区别
- SSH(Spring+hibernate+struts2)框架搭建项目详细说明
- [leetcode]371. Sum of Two Integers
- 图文混编效果之TextView、EditText中显示图片
- javascript滚轮控制模拟滚动条
- python数字图像处理(17):边缘与轮廓
- android笔记之图片适配原理
- android 支持部分关键字带下划线可点击的 TextView
- eclipse 报错 Unsupported major.minor version 52.0
- mysql查询注意事项
- Java8 新特性之七---------Nashorn JavaScript引擎、Base64、并行数组