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.
题目要求:主要是数数,但是题目要求是输出第n个字符串,即如果输入5,则输出字符串111221。
分析:按照题意,可以首先定义两个字符串,一个用来表示当前cur,一个用来表示进阶到的下一个tmp,然后遍历时每遇到相同的就使count++,然后就用'0'+count表示这个数有几个。
完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* countAndSay(int n)
{
if(n==1)
return "1";
char *cur=(char*)malloc(sizeof(char)*2),*tmp;
cur[0]='1',cur[1]=0;
int len,index,i,j,count;
for(i=2;i<=n;i++)
{
len=strlen(cur);
tmp=(char*)malloc(sizeof(char)*(3*len));
memset(tmp,0,3*len);
count=1;
for(index=1,j=0;index<len;index++)
{
if(cur[index]==cur[index-1])
count++;
else
{
tmp[j++]='0'+count;
tmp[j++]=cur[index-1];
count=1;
}
}
tmp[j++]='0'+count;
tmp[j++]=cur[len-1];
free(cur);
cur=tmp;
}
return cur;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
printf("%s\n",countAndSay(n));
}
return 0;
}