Friday, June 3, 2016

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

Java Challenge - monkeyTrouble

We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble.

monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false

My solution :
1
2
3
4
5
6
public static boolean monkeyTrouble(boolean aSmile, boolean bSmile)
{
  boolean result = !(aSmile ^ bSmile);
  return result;
}
 

Result :
Codingbat solution :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
  if (aSmile && bSmile) {
    return true;
  }
  if (!aSmile && !bSmile) {
    return true;
  }
  return false;
  // The above can be shortened to:
  //   return ((aSmile && bSmile) || (!aSmile && !bSmile));
  // Or this very short version (think about how this is the same as the above)
  //   return (aSmile == bSmile);
}