-
Notifications
You must be signed in to change notification settings - Fork 0
/
numSequence.js
49 lines (38 loc) · 1.14 KB
/
numSequence.js
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
/*
https://bigfrontend.dev/problem/A-number-sequence
121. A number sequence
Here is a sequence:
'1', first number is 1
'11', since previous number has One(1) 1
'21', since previous number has Two(2) 1s
'1211', since previous number has One(1) 2 and One(1) 1
'111221', since previous number has One(1) 1, One(1) 2, Two(2) 1s
'312211', since previous number has Three(3) 1s, Two(2) 2s, One(1) 1
....
As explained above, the sequence is generated by counting the digits of previous number.
Please create getNthNum(n) to return the n-th number string in the sequence, n starts from 1.
*/
/**
* @param {number} n - integer
* @returns {string}
*/
function getNthNum(n) {
let nthNum = "1";
while (--n) {
let res = "";
let char = nthNum[0], charCount = 1;
for (let i = 1; i <= nthNum.length; i++) {
if (nthNum[i] === char) {
charCount++;
} else {
res += `${charCount}${char}`;
char = nthNum[i];
charCount = 1;
}
}
nthNum = res;
}
return nthNum;
}
// console.log(getNthNum(1))
console.log(getNthNum(2))