一、位运算实现乘法
public static void main(String[] args) {
int a = 1;
int b = 3;
System.out.println(a * b);
}
我们小学的时候是怎么进行乘法的,按位相乘,每一位和每一位相乘.
二进制中也是一样的,按位相乘,如果被乘数二进制位是1则与乘数相乘.每次运算进行移位
public static int bitAdd(int a,int b) {
int sum = 0;
while(b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
public static int bitMul(int a,int b) {
int sum = 0;
while(b != 0) {
if((b & 1) != 0) {
sum += a;
}
a <<= 1;
b >>>= 1;
}
return sum;
}
public static void main(String[] args) {
System.out.println(bitMul(1,3));
}
二、位运算实现除法
public static void main(String[] args) {
int a = 7;
int b = 2;
System.out.println(a / b);
}
我们在用位运算实现除法时,采用逆推的方式,a / b = c,
a = c * b。
我们只需要求出a减去b向左的移位,只要满足a <= b的移位即可,每次移动多少位即a / b的结果二进制中某一位为1,以此循环倒推即可.
public static int bitAdd(int a,int b) {
int sum = 0;
while(b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
public static int negNum(int n) {
//转化为相反数
return bitAdd(~n,1);
}
public static int minus(int a,int b) {
//实现两个数相减
return bitAdd(a,negNum(b));
}
public static boolean isNeg(int n) {
//判断是否为负数
return n < 0;
}
public static int bitDiv(int a,int b) {
int x = isNeg(a) ? negNum(a) : a;
int y = isNeg(b) ? negNum(b) : b;
int res = 0;
for (int i = 30; i >= 0 ; i = minus(i,1)) {
if((x >> i) >= y) {
res |= (1 << i);
x = minus(x,y << i);
}
}
return isNeg(a) != isNeg(b) ? negNum(res) : res;
}
public static void main(String[] args) {
int a = 7;
int b = 2;
System.out.println(bitDiv(a,b));
}