Same idea.

https://discuss.leetcode.com/topic/109590/easy-to-understand-c

Here is the detailed explanation.

class Solution { public: /* Say x is the number that S[i] represents. If i was over the size of S, set x equals to i. Then start the loop. When i is odd, append '1' x times, otherwise append '2' x times. In the end, count how many '1' in S from S.begin() to S.begin() + n + 1. 如何生成这个magical string (Kolakoski Sequence)? s[i] = " 122"; 如果i是奇数, 则append s[i] 个 1 如果i是偶数, 则append s[i] 个 2 最后数一共多少个1. trick: s可以加一个空前缀" ", 这样index比较好看, 然后最后记得是s.begin() 到 s.being() + n + 1的范围内. */ // Longer but easy to understand. int magicalString2(int n) { string s = " 122"; for (int i = 3; i <= n; ++i) { if (i & 1) { s.append(s[i] - '0', '1'); } else { s.append(s[i] - '0', '2'); } } return count(s.begin(), s.begin() + n + 1, '1'); } };