[leetcode] 371. Sum of Two Integers 解题报告
来源:互联网 发布:mac下载不了软件 编辑:程序博客网 时间:2024/05/22 04:52
题目链接: 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
代码如下:
参考: http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/ 0 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)
- 图片的压缩工具类
- 进程间通信----管道
- 互联网带来了什么
- 【OpenJ_Bailian 4120】 + dp
- 归并排序(升序)
- [leetcode] 371. Sum of Two Integers 解题报告
- sublime-shortcuts
- 字符串之循环右移
- 强制修改常量值
- 简易计算机
- 基于贪心的背包解法
- static,const作用
- 小米笔记本备份、SSD分区、U盘Ghost详解及对产品的建议
- 自定义View(一)