给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。【位运算】
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) {
// write your code here, try to do it without arithmetic operators.
if (b == 0){
return a;
}
return aplusb(a ^ b , (a & b) << 1);
//用位运算代替加法时 ^表示相加 &表示进位
//二者相加时进位要左移一位,因为进位是跟上一位相加的
//!!!!!!!!注意不要忘记后面的括号!
}
};
本文介绍了一种不使用传统加法运算符实现两整数相加的方法,通过递归调用自身函数,利用位运算中的异或(^)操作完成基本的加法,同时运用按位与(&)和左移(<<)操作来处理进位。
5295

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



