-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2796-RepeatString.js
More file actions
55 lines (46 loc) · 1.36 KB
/
2796-RepeatString.js
File metadata and controls
55 lines (46 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 2796. Repeat String
// Write code that enhances all strings such that you can call the string.replicate(x) method on any string and it will return repeated string x times.
// Try to implement it without using the built-in method string.repeat.
// Example 1:
// Input: str = "hello", times = 2
// Output: "hellohello"
// Explanation: "hello" is repeated 2 times
// Example 2:
// Input: str = "code", times = 3
// Output: "codecodecode"
// Explanation: "code" is repeated 3 times
// Example 3:
// Input: str = "js", times = 1
// Output: "js"
// Explanation: "js" is repeated 1 time
// Constraints:
// 1 <= str.length, times <= 10^5
/**
* @param {number} times
* @return {string}
*/
String.prototype.replicate = function(times) {
let res = "";
for(let i = 0; i <= times - 1; i++) {
res += this;
}
return res;
}
String.prototype.replicate1 = function(times) {
let s = this.toString()
function dfs(n) {
if (n == 1) {
return s
}
var ns = dfs(n >> 1)
if (n%2) return ns+ns+s
return ns + ns
}
return dfs(times)
}
console.log("hello".replicate(2)) // hellohello
console.log("code".replicate(3)) // codecodecode
console.log("js".replicate(1)) // js
console.log("hello".replicate1(2)) // hellohello
console.log("code".replicate1(3)) // codecodecode
console.log("js".replicate1(1)) // js