Wednesday 14 March 2018

Algorithms | Add two number

Add two numbers with all corner case scenarios.

Corner cases
1. Both numbers are negative
          a. Sum is negative - Will work fine
          b. Sum is positive -
                   If the sum is positive or zero, this is only possible when the number is out of Max Integer range.
2. Both numbers are negative
          a. Sum is positive - Will work fine
          b. Sum is negative -
                   If the sum is negative, this is only possible when the number is out of Min Integer range.


public class AddTwoNumbers {

     /**
      * Adds two number.
      *
      * @param a
      * @param b
      * @return sum
      */
     private static int add(int a, int b) {

           int sum = a + b;
           boolean flag = true;

           if ((flag = a > 0 && b > 0) || (a < 0 && b < 0)) {
                if ((flag && sum < 0) || (!flag && sum >= 0)) {
                     throw new ArithmeticException("Overflow");
                }
           }
           return sum;
     }

     /**
      * Driver method.
      *
      * @param args
      */
     public static void main(String[] args) {

           int sum1 = add(Integer.MIN_VALUE, 0);
           System.out.println("Sum 1 " + sum1);

           int sum2 = add(Integer.MAX_VALUE, -5);
           System.out.println("Sum 2 " + sum2);

           // Overflow due to both minimum negative values.
           try {
                add(Integer.MIN_VALUE, Integer.MIN_VALUE);
           } catch (Exception e) {
                System.err.println(e.getMessage());
           }

           // Overflow due to both maximum positive values.
           try {
                add(Integer.MAX_VALUE, Integer.MAX_VALUE);
           } catch (Exception e) {
                System.err.println(e.getMessage());
           }

           int sum5 = add(4, 5);
           System.out.println("Sum 5 " + sum5);

           int sum6 = add(-4, -5);
           System.out.println("Sum 6 " + sum6);
     }
}
Related Posts Plugin for WordPress, Blogger...