Friday, June 3, 2016

Java Challenge - frontBack

Given a string, return a new string where the first and last chars have been exchanged.
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"

My Solution :
1
2
3
4
5
6
7
8
public String frontBack(String str) {
  if (str.length() == 0 || str.length() == 1) return str;
  char temp1 = str.charAt(0);
  char temp2 = str.charAt(str.length()-1);
  String temp3 = str.substring(1, str.length()-1);
  String result = temp2+temp3+temp1;
  return result;
}

CodingBat's Solution :
1
2
3
4
5
6
7
8
public String frontBack(String str) {
  if (str.length() <= 1) return str;
  
  String mid = str.substring(1, str.length()-1);
  
  // last + mid + first
  return str.charAt(str.length()-1) + mid + str.charAt(0);
}

Weeew... My solution looks so bad... :v :v :v
But it doesn't matter, I'm just getting started... B-)

Java Challenge - WarmUp 1

Link : http://codingbat.com/prob/p187868
Task :
The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in.

sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true

Solution :

1
2
3
4
5
6
7
public boolean sleepIn(boolean weekday, boolean vacation) {
  if(!weekday || vacation)
  {
    return true;
  }
  return false;
}

Result :