题目:The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
刚拿到题目的时候我也是蒙蔽的不知道题目啥意思,要是想不出来大家不要觉得自己的智商不够啊。其实题目的意思是,“用数字表达上一个数”。比如上一个数是“1211”,出现了1个1,1个2,以及2个1,所以输出就是“111221”。理解题目了下面就好办了。
本题目要用到一点递归的思想,代码如下:
//将数字转换成字符串
string int2string(int x){
ostringstream stream;
stream<<x;
string k = stream.str();
return k;
}
//将字符串的数字用数字“数”出来
string getStr(string numStr){
int i=0,j=1,counts=1;
string result="";
for(;j<numStr.length();++i,++j){
if(numStr[i]!=numStr[j]){
result +=int2string(counts)+numStr[i];
counts=1;
continue;
}
else
counts++;
}
result +=int2string(counts)+numStr[i];
return result;
}
//给出n时,输出第n个数数。主调函数。
string countAndSay(int n) {
if(n==1)
return "1";
string preString = countAndSay(n-1);
return getStr(preString);
}