C++
1 class Solution { 2 public: 3 /** 4 * @param n the nth 5 * @return the nth sequence 6 */ 7 string countAndSay(int n) { 8 // Write your code here 9 if (0 == n) {10 return "";11 }12 string pre = "1";13 for (int i = 1; i < n; i++) {//从第2个(i=1)开始14 char ch = pre[0];15 string cur = "";16 int cnt = 0;17 for (int j = 0; j < pre.size(); j++) {18 if (pre[j] == ch) {19 cnt ++;20 } else {21 cur = cur + itostr(cnt) + ch;22 ch = pre[j];23 cnt = 1;24 }25 }26 if (cnt != 0) {//处理后边的字符27 cur = cur + itostr(cnt) + ch;28 }29 pre = cur;30 cur = "";31 }32 return pre;33 34 }35 string itostr(int i) {//自定义int转string函数36 char str[10];37 //itoa(str,i,10);->only support Windows38 sprintf(str, "%d", i);//support any platforms39 return str;40 }41 };