[LeetCode] Count and Say

This problem is purely to test your coding ability. Just go ahead :-)

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string num = "1";
 5         for (int i = 1; i < n; i++)
 6             num = say(num);
 7         return num;
 8     } 
 9 private:
10     string say(string& num) {
11         string s;
12         int n = num.length(), i = 0, j, k;
13         for (int i = 0; i < n; i = j, k = 0) {
14             k = 1, j = i + 1;
15             while (j < n && num[j] == num[i]) j++, k++;
16             s += char(k + '0');
17             s += num[i];
18         }
19         return s;
20     }
21 };

 

posted @ 2015-08-17 17:06  jianchao-li  阅读(183)  评论(0编辑  收藏  举报