Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: it seems to me that the bounds checking test for overflow was deficient so i added a second code example i have more confidence in.

...

Code Block
bgColor#ccccff
public int do_operationadd(int a, int b) throws ArithmeticException {
   long temp = (long)a + (long)b;
   if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
     throw new ArithmeticException("Out of range");
   }
   return (int)temp; // Value within range; can perform the addition
}

...

Code Block
bgColor#ccccff
public int do_operationadd(int a, int b) throws ArithmeticException {
  if( b > 0 ? a > Integer.MAX_VALUE - b : a < Integer.MIN_VALUE - b ) {
    throw new ArithmeticException("Not in range");
  }
  return a + b;  // Value within range so addition can be performed
}
Code Block
bgColor#ccccff

public int add(int a, int b) throws ArithmeticException {
  if (((a > 0) && (b > 0) && (a > (Integer.MAX_VALUE - b))) 
   || ((a < 0) && (b < 0) && (a < (Integer.MIN_VALUE - b)))) {
     throw new ArithmeticException("Not in range");
}
else {
  return a + b;  // Value within range so addition can be performed
}

Compliant Solution (Use BigInteger Class)

...