题目
Repeats the given string n
times.(复制指定的字符串n次)
期望结果
/**
* Repeats the given stringn
times.
* * repeat(‘', 3)
* // => '**’
*
* repeat(‘abc’, 2)
* // => ‘abcabc’
*
* repeat(‘abc’, 0)
* // => “”
**/
代码实现
【js篇】
1.方法1:
function repeat(string,n){let result = '';//边界情况处理if(!string || n < 1 || n > Number.MAX_SAFE_INTEGER){return result}do {result += stringn--} while (n >= 1);return result;}const demo1 = repeat('*',3)console.log("🚀 ~ demo1:", demo1)const demo2 = repeat('abc',2)console.log("🚀 ~ demo2:", demo2)const demo3 = repeat('abc',0)console.log("🚀 ~ demo3:", demo3)
2.方式2:
function repeat2(string,n){let result = '';//边界情况处理if(!string || n < 1 || n > Number.MAX_SAFE_INTEGER){return result}do {// Leverage the exponentiation by squaring algorithm for a faster repeat.// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.if(n % 2){result += string}n = Math.floor( n / 2 );if(n){string += string}} while (n);return result;}const demo4 = repeat('*',3)console.log("🚀 ~ demo4:", demo4)
【java篇】
public class repeat {public static void main(String[] args) {/*** Repeats the given string `n` times.* * repeat('*', 3)* // => '***'** repeat('abc', 2)* // => 'abcabc'** repeat('abc', 0)* // => ''**/String str = repeat("*",3);System.out.println(str);String str1 = repeat("abc",2);System.out.println(str1);String str2 = repeat("abc",0);System.out.println(str2);}public static String repeat(String string,int n){String result = "";if(string.isEmpty() || n < 1 || n > Integer.MAX_VALUE){return result;}do {if(n % 2 > 0){result +=string;}n = (int)(Math.floor( n / 2));if(n > 0){string += string;}}while (n > 0);return result;}
}