用+,-, <<, >>来实现 *, / 。
package com.pande.jobhunt.problem;
//用+,-, <<, >>来实现 *, / 。
public class ImplemeneMultiAndDevideUsingPlusAndShift {
public static long multiply(long a, long b) {
long result = 0;
long poistive = 1;
if (a < 0) {
a = -a;
poistive = -poistive;
}
if (b < 0) {
b = -b;
poistive = -poistive;
}
long remain = 0;
while (b > 0) {
remain = b % 2;
result += a * remain;
b = b >> 1;
a = a << 1;
}
return poistive * result;
}
// a / b
public static long divide(long a, long b) {
long result = 0;
long poistive = 1;
if (a < 0) {
a = -a;
poistive = -poistive;
}
if (b < 0) {
b = -b;
poistive = -poistive;
}
while (a >= b) {
long d = 1;
long c = b;
while (c <= a) {
a = a - c;
result += d;
c <<= 1;
d <<= 1;
}
}
return poistive * result;
}
public static void main(String[] args) {
long t = multiply(-5, -6);
System.out.println(t);
long n = divide(71, 5);
System.out.println(n);
}
}