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.
题意:伯爵说,
1读为“一个1”输出11
11读为“两个1”输出21
………..
给定一个n,输出第n个字符串序列
Notes:整型序列用字符串表示。
解题思路:这涉及的知识点是字符串的操作,字符串转整型,还有就是细节问题,对最后一个字符的操作,对相同字符的统计并作为下一个字符串的字符。
C语言实现代码:
/**
* 解题思路:涉及到字符串的简单操作,需要获取字符串中相同字符的个数并作为下一个字符串的字符
* 输入的n代表去第几个字符串输出,这同时也需要求出前面字符串的值,就行Fibonacci数列一样,求后一个字符串需要知道前一个字符串
*/
void CountSay(char *str1, char *str2){
int count, i, j;
count = 1;
j = i = 0;
while(*(str1+i+1) != '\0'){
if(*(str1+i) == *(str1+i+1)){
i++;
count++;
}else{
*(str2 + j++) = count + '0';
*(str2 + j++) = *(str1+i);
i++;
count = 1;
}
}
*(str2 + j++) = count + '0';
*(str2 + j++) = *(str1+i);
}
char *countAndSay(int n) {
char *str1, *str2;
int i;
str1 = (char *)malloc(9999*sizeof(char));//初始化数组大小
str2 = (char *)malloc(9999*sizeof(char));
memset(str1, 0 ,9999);
memset(str2, 0, 9999);
strcpy(str2, "1");
for(i = 1; i <n; i++){
CountSay(str2, str1);
strcpy(str2,str1);
}
return str2;
}
本文介绍了一种特殊的整型序列生成方法——计数与描述序列,并提供了详细的C语言实现代码。该序列从1开始,后续每一项都是对其前一项的描述。例如,1被描述为“一个1”,即11;11被描述为“两个1”,即21。文章通过实例解释了序列生成的过程,并提供了一个完整的C语言实现示例。
853

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



