Problem
IF we have 2 numbers a, b
Thanks.
Write a method to implement *, – , / operations You should use only the + operator.Solution
IF we have 2 numbers a, b
- a * b can be implemented as adding a for b times.Take care of overflow as a*b may result in overflow.
- a – b can be implemented as addition of a and -b.
- a / b can be implemented as finding how many times you need to add b, until getting a.
public static int negate(int number) {
return ~number + 1;
}
public static int abs(int number) {
return number < 0 ? negate(number) : number;
}
public static int multiply(int a, int b) {
int multiplier = Math.min(abs(a), abs(b));
int multiplicant = (multiplier == abs(a) ? abs(b) : abs(a));
if(multiplier==0 || multiplicant==0)
return 0;
int result = 0;
for (int i = 0; i < multiplier; i = i + 1) {
long holdResult = result+multiplicant;
if(holdResult>Integer.MAX)
throw new java.lang.ArithematicException("Overflow in integer");
result = (int)holdResult;
}
if (abs(a) == a) { // a >= 0
if (abs(b) == b) // b >= 0
return result;
else
// b < 0;
return negate(result);
} else { // a < 0
if (abs(b) == b) // b >= 0
return negate(result);
else
// b < 0;
return result;
}
}
public static int substract(int a, int b) {
return a + negate(b);
}
public static int divide(int a, int b) {
if (b == 0) {
throw new java.lang.ArithmeticException("Divide by 0.");
}
int divident = abs(a);
int divisor = abs(b);
int quotient = 0;
while (divident >= divisor) {
divident = substract(divident, divisor);
quotient = quotient + 1;
}
if (abs(a) == a) { // a >= 0
if (abs(b) == b) // b >= 0
return quotient;
else
// b < 0;
return negate(quotient);
} else { // a < 0
if (abs(b) == b) // b >= 0
return negate(quotient);
else
// b < 0;
return quotient;
}
}
Thanks.







0 comments:
Post a Comment