Saturday, June 4, 2016

Java Challenge - stringTimes - warm_up_2

Given a string and a non-negative int n, return a larger string that is n copies of the original string.
stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"

Hisoka :
1
2
3
4
5
6
7
8
9
public String stringTimes(String str, int n) {
  String result="";
  while(n>0)
  {
 result += str;
 n -= 1;
  }
  return result;
}

Output :

Codingbat:
1
2
3
4
5
6
7
public String stringTimes(String str, int n) {
  String result = "";
  for (int i=0; i<n; i++) {
    result = result + str;  // could use += here
  }
  return result;
}

Friday, June 3, 2016

Java Challenge - nearHundred - warm_up

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

nearHundred(93) → true
nearHundred(90) → true
nearHundred(89) → false

Hisoka's code:
1
2
3
public boolean nearHundred(int n) {
  return((Math.abs(n-100) <= 10)||(Math.abs(200-n) <= 10));
}

Output:

Codingbat code:
1
2
3
4
public boolean nearHundred(int n) {
  return ((Math.abs(100 - n) <= 10) ||
    (Math.abs(200 - n) <= 10));
}

Hohoho... Mirip... :D