Problem:
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"
Solution:
public String frontTimes(String str, int n) { int len = str.length(); String temp = ""; if (len < 4) { for (int i = 0; i < n; i++) { temp += str; } } else { for (int j = 0; j < n; j++) { temp += str.substring(0,3); } } return temp; }
private final String frontTimes(String word, int n) {
ReplyDeleteif(n == 0){
return "";
}
final String front = (word.length() <= 3)? word: word.substring(0, 3);
final String repeat = (n <= 1)? front: front + frontTimes(front, n - 1);
return repeat;
}
int len =3;
ReplyDeleteif(len> str.length()){
len=str.length();
}
String result = "";
for (int i=0; i<n; i++) {
result= result + str.substring(0, len);
}
return result;
public String frontTimes(String str, int n) {
ReplyDeleteif (n == 0) return "";
if (str.length()<4) return str + frontTimes(str, n-1);
return frontTimes(str.substring(0, 3), n);
}
Another way
ReplyDeletepublic String frontTimes(String str, int n) {
int substring = 3;
if (substring > str.length()) {
substring = str.length();
}
return String.join("", Collections.nCopies(n, str.substring(0, substring)));
}
two ways:
ReplyDelete1)
function frontTimes(str, n){
const stringSplit = str.split("");
let arr = [];
for(let i = 0; i <= 2; i++){
arr.push(stringSplit[i])
}
return arr.join("").repeat(n)
}
2)(and the simpler one)
function frontTimes(str, n){
return str.substring(0,3).repeat(n)
}
in JavaScript!!
Delete