Problem:
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"
Solution:
public String stringTimes(String str, int n) { String temp = ""; for (int i = 0; i < n; i++) temp += str; return temp; }
public String stringTimes(String word, int n) {
ReplyDeleteif(n == 0){
return "";
}
if(n > 1){
return word + stringTimes(word, n - 1);
}
return word;
}
I think it is easier to do it without using recursion.
Deletepublic String stringTimes(String str, int n) {
ReplyDeleteString count="";
for(int i=0; i=str.length()||n<=str.length())
count+=str;
}
return count;
}
This comment has been removed by the author.
ReplyDeletereturn str.repeat(n);
ReplyDeleteAnother way
ReplyDeletereturn String.join("", Collections.nCopies(n, str));