Count and Say
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.
» Solve this problem不知道怎么回事,用strcat就老是会有run error。
class Solution {
public:
char buf[10000];
char dest[10000];
string countAndSay(int n) {
buf[0] = '1';
buf[1] = '\0';
for (int i = 1; i < n; i++) {
convert(buf, dest);
memcpy(buf, dest, sizeof(buf));
}
return string(buf);
}
void convert(char* src, char* dest) {
char num[10000];
int cnt[10000];
memset(cnt, 0, sizeof(cnt));
memset(num, 0, sizeof(num));
int idx = -1;
int len = strlen(src);
char *s = src, *end = src + len;
char prev = 'x';
while (s != end) {
if (prev == *s) {
cnt[idx]++;
} else {
cnt[++idx] = 1;
num[idx] = *s;
prev = *s;
}
s++;
}
int id = 0;
char tmp[32];
for (int i = 0; i <= idx; i++) {
dest[id++] = cnt[i] + '0';
dest[id++] = num[i];
}
dest[id] = '\0';
return;
}
};

本文介绍了一个有趣的数学序列——计数并描述序列,并提供了一种使用 C++ 实现的方法来生成该序列的第 n 项。通过示例解释了序列的工作原理,包括如何从初始值 1 开始迭代生成后续的每一项。
492

被折叠的 条评论
为什么被折叠?



