LeetCode 371.Sum of Two Integers 解题报告
来源:互联网 发布:书法软件哪个最好 编辑:程序博客网 时间:2024/05/22 12:16
LeetCode 371. Sum of Two Integers 解题报告
题目描述
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
示例
Given a = 1 and b = 2, return 3.
限制条件
不能使用+和-两个运算符。
解题思路
题目看起来很简单,但是要是没有找对方向,怕是怎么也做不出吧。
我一开始就是在错误的方向里钻了牛角尖,最初的想法是通过其他的数学运算来完成加法的功能:
但是当
后来也有想着用字符串表示数字之类的奇怪的方法但都不行,终于还是查看了一下LeetCode里这道题的标签,是bit manipulation,于是茅塞顿开。
这道题正确的思路应该是使用位操作来完成加法的效果。二进制的加法经过两个步骤:
1.两个二进制数相加,得到临时结果。
2.将临时结果与进位相加,得到最终的结果。
注意执行二进制加法时是对所有的位同时操作。步骤中有两个重要的概念,一个是加法操作,其实是通过位的异或运算^完成;另一个是进位,通过位的相与运算&能够找到进位的位置,再通过左移1位就能得到进位(不信可以自己演算一下)。循环进行以上两个步骤,上一次循环产生的进位及加法结果会成为下一次的两个加法操作数。当没有下一次进位时,临时结果就是最终结果,计算就结束了。
把第一次运算中的第一个运算数看做是一个临时结果,第二个运算数看做是一个进位的话,那么总结起来就是:计算好下一次进位,临时结果与当前进位异或,检查下一次进位是否为0,否就进入下一次循环,代码直观地反映了这一点。
代码
class Solution {public: int getSum(int a, int b) { int c = 0; do { // next carry bit's position c = a & b; // a is current result and b is current carry bit a = a ^ b; // next carry bit b = (c << 1); } while(c); return a; }};
总结
像这些特殊的题目还是要多做多积累经验,不然连方向都找不准。
今天又长了新知识,加油!
- [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)
- 漫谈程序员系列:咦,你也在混日子啊
- [学习笔记]java并发编程目录
- 漫谈程序员系列:怎么告别“混日子”
- Java基础 - 3.运算符
- 外键约束的参照操作
- LeetCode 371.Sum of Two Integers 解题报告
- 51串行口通信
- 双目立体视差图计算
- 解决Error LNK2019: unresolved external symbol
- 学习笔记-windows下配置nginx+php
- Linux集群时间同步设置
- JAVA反射系列之Field,java.lang.reflect.Field使用获取方法。
- 最长单增子序列-动态规划
- 一些基本形态学算法------区域填充算法