Saturday, June 4, 2016

Java Challenge - frontTimes - warm_up_2

Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;

frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Chocolate", 3) → "ChoChoCho"
frontTimes("Abc", 3) → "AbcAbcAbc"
Hisoka :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public String frontTimes(String str, int n) {
   String result = "";
   if(str.length() > 2)
   {
     String x = str.substring(0, 3);
     while(n>0)
      {
   result += x;
   n -= 1;
      }
   }else
     {    
       while(n>0)
       {
         result += str;
         n -= 1;
       }
     }
   return result;
}

Hasilnya :

Codingbat :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public String frontTimes(String str, int n) {
  int frontLen = 3;
  if (frontLen > str.length()) {
    frontLen = str.length();
  }
  String front = str.substring(0, frontLen);
  
  String result = "";
  for (int i=0; i<n; i++) {
    result = result + front;
  }
  return result;
}

No comments:

Post a Comment