Repeat Character N Times

后端 未结 23 2545
栀梦
栀梦 2020-11-22 11:51

In Perl I can repeat a character multiple times using the syntax:

$a = \"a\" x 10; // results in \"aaaaaaaaaa\"

Is there a simple way to ac

23条回答
  •  死守一世寂寞
    2020-11-22 12:20

    Another interesting way to quickly repeat n character is to use idea from quick exponentiation algorithm:

    var repeatString = function(string, n) {
        var result = '', i;
    
        for (i = 1; i <= n; i *= 2) {
            if ((n & i) === i) {
                result += string;
            }
            string = string + string;
        }
    
        return result;
    };
    

提交回复
热议问题