【算法练级js+java】重复给定字符n次

题目

Repeats the given string n times.(复制指定的字符串n次)

期望结果

/**
* Repeats the given string n 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 += string
          n--
        } 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;
    }
}

在这里插入图片描述

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值