[leetcode] 371. Sum of Two Integers 解题报告
来源:互联网 发布:matlab在线编程 编辑:程序博客网 时间:2024/05/01 20:22
题目链接: 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+5, 其二进制形式为11: 1011, 5: 0101
1. 那么两个位置都为1的地方就需要进位, 所以进位值就为0001. 原位置两个数相加的结果为那个位置值的异或即1110, 即两个位置值如果不一样就为1, 一样的话要么两个位置原来值都为0结果也为0, 要么进位, 那么结果依然是0.
2. 接下来就要把进位位和下一位相加, 所以进位值左移一位,即0001变为0010, 重复上面操作可得新的进位值为0010, 原位置异或(即相加)结果为1100.
3. 继续重复上面操作直到进位为0, 可得到最终结果10000, 即16
代码如下:
class Solution {public: int getSum(int a, int b) { while(b) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; }};参考: http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/
4 0
- [leetcode] 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 解题报告
- 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 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)
- Dubbo整合maven+spring+springmvc+mybatis
- 编写函数 unsigned int reverse_bit(unsigned int value); 这个函数的返回值吧value的二进制位模式从左到右翻转后的值。
- 6-2DBMS的故障恢复
- 6-3DBMS并发控制
- 【leetcode】9. Palindrome Number
- [leetcode] 371. Sum of Two Integers 解题报告
- JavaScript操作SVG 提高篇
- 我所理解的String
- Problem N
- GridView高度填充屏幕
- LeetCode - 7. Reverse Integer
- Unity插件 - MeshEditor(三) 面片破碎&网格破碎
- Https Tomcat CSR生成 以及相关操作
- php