Saturday, February 28, 2015

Operations


Write a method to implement *, - , / operations.You should use only the + operator.
It is straight forward to convert plus to minus: a - b = a + (-b). But we need to first write a negative. To get the negative counterpart of a number, we simply add -1 (if the number is positive) or 1 (if the number is negative) to both a and 0, then when a reaches 0, the other number becomes the negative (positive) counterpart of a.

Multiplication, think about when we were in elementary school, how do we learn multiplication. We add number by number, 2 * 3 is 2 + 2 + 2 or 3 + 3 since the later requires less operation. The same here, use a loop.

Division is similar, 21 / 7 is number of 7s that can be subtracted from 21 until it is 0. Note that in order to make it compatible with Java's division for int, i.e., return floor of the number if the quotient is not an integer.

For both multiplication and division, negative sign needs to be taken into account.


public class operations {
 public static int negative(int a) {
  if (a == 0)
   return a;
  int neg = 0;
  int d = a < 0 ? 1 : -1;
  while (a != 0) {
   neg += d;
   a += d;
  }
  return neg;
 }
 public static int subtract(int a, int b) {
  return a + negative(b);
 }
 public static int abs(int a) {
  return a < 0 ? negative(a) : a;
 }
 public static int mutiply(int a, int b) {
  if (a < b) {
   int tmp = a;
   a = b;
   b = tmp;
  }
  boolean isNegative = false;
  if ((a < 0 && b > 0) || (a > 0 && b < 0))
   isNegative = true;
  a = abs(a);
  b = abs(b);
  for (int i = 1; i < b; i++)
   a += a;
  return isNegative ? negative(a) : a;
 }
 
 public static int divide(int a, int b) {
  if (b == 0)
   throw new ArithmeticException("Divide by zero!");
  boolean isNegative = false;
  if ((a < 0 && b > 0) || (a > 0 && b < 0))
   isNegative = true;
  a = abs(a);
  b = abs(b);
  int rst = 0;
  while (a > 0) {
   a -= b;
   rst++;
  }
  if (a < 0)
   rst--;
  return isNegative ? negative(rst) : rst;
 }
 public static void main(String[] args) {
  System.out.println(divide(-24, 3));

 }

}

No comments:

Post a Comment