371 Sum of Two Integers用位操作实现两个数的加法——递归
来源:互联网 发布:js iframe 跳转 编辑:程序博客网 时间:2024/06/06 08:54
Write a function that adds two numbers. You should not use + or any arithmetic operators.
这道题让我们实现两数相加,但是不能用加号或者其他什么数学运算符号,那么我们只能回归计算机运算的本质,位操作Bit Manipulation,我们在做加法运算的时候,每位相加之后可能会有进位Carry产生,然后在下一位计算时需要加上进位一起运算,那么我们能不能将两部分拆开呢,我们来看一个例子759+674
1. 如果我们不考虑进位,可以得到323
2. 如果我们只考虑进位,可以得到1110
3. 我们把上面两个数字假期323+1110=1433就是最终结果了
然后我们进一步分析,如果得到上面的第一第二种情况,我们在二进制下来看,不考虑进位的加,0+0=0, 0+1=1, 1+0=1, 1+1=0,这就是异或的运算规则,如果只考虑进位的加0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是与的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,我们直接返回第一步的结果,参见代码如下:
int add(int a,int b){if(b==0) return a;int sum=a^b;int carry=(a&b)<<1;return add(sum,carry);//递归运算直到进位b==0的时候结束}
阅读全文
0 0
- 371 Sum of Two Integers用位操作实现两个数的加法——递归
- leetcode 371. Sum of Two Integers 位运算 + 加法操作
- [leetcode] Sum of Two Integers--用位运算实现加法运算
- [LeetCode] 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 (位运算实现加法)
- LeetCode 371. Sum of Two Integers不用加减实现加法
- leetcode 371. Sum of Two Integers(不用+ -实现加法)
- leetcode-371. Sum of Two Integers 位运算的应用,递归,按位异或a^b
- 位操作-leetcode 371. Sum of Two Integers
- Sum—LeetCode-371 Sum of Two Integers
- LeetCode—371. Sum of Two Integers
- LeetCode 371 Sum of Two Integers (位运算)
- [Leetcode #371]Sum of Two Integers 不使用加法运算符完成加法运算
- 371Sum of Two Integers
- 371 Sum of Two Integers
- RecyclerView完全解析,让你从此爱上RecyclerView
- Vim技能修炼教程(4)
- c++判断硬盘是否连接、修改指定盘符、读取配置文件、获取exe路径
- sql查询结果转XML和JSON
- 域名被纳入无形资产征税是好事还是坏事呢?
- 371 Sum of Two Integers用位操作实现两个数的加法——递归
- Invoke和BeginInvoke理解
- jQuery中的on,find,load方法
- Lucene和Solr 学习目录
- jquery 判断对象是否为空,判断后台传回来的data数据是否为空
- python字符串
- POJ 3621 Sightseeing Cows(最优比率环/01分数规划)
- Regex操作
- Golang调用Python