题目:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
public class Solution {
public int getSum(int a, int b) {
if(a==0)return b;
if(b==0)return a;
while(b!=0){
int carry=a&b;
a=a^b;
b=carry<<1;
}
return a;
}
}很简单,其实位运算中,异或表示不带进位的加法,与可以求出两个数的的进位,用循环把进位加上去,直至进位为0,就酱子0.0
递归写法也很简单:
public int getSum(int a, int b) {
return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
}同理,可以求出减法的位运算
public static int sub(int a,int b){
int carry=0;
while(b!=0){
carry=(~a)&b;//a&(~b+1)
a=a^b;
b=carry<<1;
}
return a;
}递归写法为:
public int getSubtract(int a, int b) {
return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
}其中 -b=~a+1;
public int negate(int x) {
return ~x + 1;
}
本文介绍了一种利用位运算实现整数加法和减法的方法,避免使用传统的加减运算符。通过异或运算实现不带进位的加法,与运算求出进位,再将进位左移后加入结果中,重复此过程直至没有进位。同样地,文中也给出了减法的位运算实现。
755

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



