Sum of two integer number
来源:互联网 发布:头条科技工作 知乎 编辑:程序博客网 时间:2024/05/17 00:55
题目:两个整型数组相减,不能使用“+”和“-”(注意:两数相加并不知道两个数字是正书还是负数)
思路:在不能使用运算符号的条件下,只能考虑最底层的位运算
方法:
实现两数相加,但是不能用加号或者其他什么数学运算符号,那么我们只能回归计算机运算的本质,位操作Bit Manipulation,我们在做加法运算的时候,每位相加之后可能会有进位Carry产生,然后在下一位计算时需要加上进位一起运算,那么我们能不能将两部分拆开呢,我们来看一个例子759+674
1. 如果我们不考虑进位,可以得到323
2. 如果我们只考虑进位,可以得到1110
3. 我们把上面两个数字假期323+1110=1433就是最终结果了
然后我们进一步分析,如果得到上面的第一第二种情况,我们在二进制下来看,不考虑进位的加,0+0=1, 0+1=1, 1+0=1, 1+1=0,这就是异或的运算规则,如果只考虑进位的加0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是与的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,我们直接返回第一步的结果
代码:
方法一:
int sum(int a,int b){
if(b==0) return a;
int sum = a^b;
int carry = (a&b)<<1;
return sum(sum,carry);
}
方法二(将方法一写成一行代码):
int sum(int a,int b){
return b == 0?a:sum(a^b,(a&b)<<1);
}
方法三:
int sum(int a,int b){
while(b){
a = a^b;
int carry = (a&b)<<1;
b=carry;
}
return a;
}
- Sum of two integer number
- LeetCode——two sum of integer
- sum of two 20-based number
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- sum of two integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- 四旋翼位置控制之-GPS水平位置控制
- jQuery $.each用法
- 82. Remove Duplicates from Sorted List II
- [Android问答] px、dp和sp,这些单位有什么区别?
- 并发编程四:Synchronized关键字
- Sum of two integer number
- LinearLayout布局中Layout_weight的深刻理解-为何需设置android:layout_width="0dp"
- node.js切换模板引擎
- oracle 密码中包括了“@”字符串
- POJ 2387 Til the Cows Come Home
- 经验分享之在linux虚拟机上实现svn的备份还原
- 【Android移动开发技术】最常用的GitHub上优秀的 Android 开源项目
- 【白话设计模式一】代理模式(Proxy)
- 最短路 ( SPFA )——Ramzi ( Gym 101061 C )