问题来源:LeetCode
问题描述:
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.
----------------------------------------------------------------------------------------------------------
一、运行截图
二、程序代码
int main()
{
char s[1000] = {'1','\n'};
char *p, *q;
int count = 1;
int i, m = 26;
p = q = s;
q += 2;
while(m--) //m为预设定的要统计的次数
{
count = 1; //重置统计标志为1,代表新的统计即将开始。
while(*p == *(p+1))
{
count++; //若p后面字符与p当前字符相同,则更新当前字符的个数。
p++; //同时指针p后移。
}
*q++ = count +'0'; //将统计的字符个数放在往右的第一个空位置。
*q++ = *p; //将刚刚统计过个数的字符放在紧邻的空位置
if('\n' == *(p+1))
{
*q++ = '\n'; //若指针p后面紧邻的位置为'\n',则说明当前行已统计完毕,存放已统计字符的行也该换到下一行了。
p += 2; //指针p换行
}
else
p++; //否则若p后面还有未统计的不同字符,则指针p移动到紧邻的还未统计的字符处,准备开始统计新字符个数。
}
puts(s);//最终输出统计到的结果。
}
三、结语
越编程越觉得写程序最重要的就是构思,即并不是一上来就开始写,而是得先在大脑里对要实现的功能进行分析、拆分。甚至光是想还不行,动动笔在稿纸上写一写也是很必需的。确定好程序该怎么写后就可以正式开始编写代码了。当然了,在编写的过程中还是会遇到各种意想不到的小BUG,耐心点就好了。