3.22 学会了用位运算做加减法
以后有了时间再学习一下乘除法,以及位运算的一些妙用。
class Solution {
/*
* param a: The first integer
* param b: The second integer
* return: The sum of a and b
*/
public int aplusb(int a, int b) {
if (a == 0){
return b;
}
if (b == 0){
return a;
}
int sum = a ^ b; //异或,不同的时候为1,相同的时候为0;
int carry = (a & b) << 1 ;//进位操作
return aplusb(sum, carry) ;
// write your code here, try to do it without arithmetic operators.
}
//获得相反数 ~a + 1
public int negativeNum(int a){
return(~a,1);
}
public int asubb(int a, int b){
return aplusb(a,negativeNum(b));
}
};
本文介绍了一种使用位运算实现整数加减法的方法。通过异或运算处理不考虑进位的情况,同时利用与运算结合左移运算来确定进位情况。文中还涉及了如何获取一个数的相反数,并通过相反数实现减法运算。
757

被折叠的 条评论
为什么被折叠?



