Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 19, 2013 14:18
Show Gist options
  • Select an option

  • Save pdu/4986303 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4986303 to your computer and use it in GitHub Desktop.
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. http://leetcode.c…
class Solution {
public:
string countAndSay(int n) {
string ans = "1";
while (--n) {
string tmp = ans;
ans.clear();
int cnt;
char num;
char buf[1024];
for (int i = 0; i < tmp.length(); ++i) {
if (i == 0) {
cnt = 1;
num = tmp[0];
}
else if (tmp[i] == tmp[i - 1])
cnt++;
else {
sprintf(buf, "%d%c", cnt, num);
ans.append(buf);
cnt = 1;
num = tmp[i];
}
}
sprintf(buf, "%d%c", cnt, num);
ans.append(buf);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment