Friday, June 3, 2016

Java Challenge - diff21

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.

diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
Hisoka's Sol:
1
2
3
4
5
6
7
public int diff21(int n) {
  if(n <= 21) return 21-n;
  else
  {
    return 2*Math.abs(n-21);
  }
}
Result:

Codingbat Sol:
1
2
3
4
5
6
7
public int diff21(int n) {
  if (n <= 21) {
    return 21 - n;
  } else {
    return (n - 21) * 2;
  }
}

Java Challenge - sumDouble

Given two int values, return their sum. Unless the two values are the same, then return double their sum.

sumDouble(1, 2) → 3
sumDouble(3, 2) → 5
sumDouble(2, 2) → 8

Hisoka's Solution :
1
2
3
4
public int sumDouble(int a, int b) {
  if(a == b) return (a+b)*2;
  else return a+b;
}
Result:
Codingbat Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public int sumDouble(int a, int b) {
  // Store the sum in a local variable
  int sum = a + b;
  
  // Double it if a and b are the same
  if (a == b) {
    sum = sum * 2;
  }
  
  return sum;
}