Skip to content

Commit 994739c

Browse files
committed
Magical String
1 parent afe2375 commit 994739c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Source : https://leetcode.com/problems/magical-string/
2+
// Author : Han Zichi
3+
// Date : 2017-01-10
4+
5+
/**
6+
* @param {number} n
7+
* @return {number}
8+
*/
9+
var magicalString = function(n) {
10+
let arr = [1, 2, 2];
11+
let index = 2;
12+
13+
while (arr.length < n) {
14+
let item = arr[arr.length - 1] === 2 ? 1 : 2;
15+
for (let i = 0; i < arr[index]; i++)
16+
arr[arr.length] = item;
17+
index++;
18+
}
19+
20+
let ans = 0;
21+
for (let i = 0; i < n; i++)
22+
(arr[i] === 1) && ans++;
23+
24+
return ans;
25+
};

0 commit comments

Comments
 (0)