Friday, June 3, 2016

Java Challenge - lastDigit - warm_up

Given two non-negative int values, return true if they have the same last digit, such as with 27 and 57. Note that the % "mod" operator computes remainders, so 17 % 10 is 7.

lastDigit(7, 17) → true
lastDigit(6, 17) → false
lastDigit(3, 113) → true

Hisoka's Answer:
1
2
3
4
public boolean lastDigit(int a, int b) {
  if(a%10 == b%10) return true;
  else return false;
}

Result:

Codingbat Answer:
1
2
3
4
public boolean lastDigit(int a, int b) {
  // True if the last digits are the same
  return(a % 10 == b % 10);
}

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;
  }
}