题目
假定以下是一组有规律的整数序列
1,11,21,1211,111221,……
起始是”一个1“,那么接下来的数就是11
11可以被计为”两个1“,接下来的数就是21
然后21被计为”一个2一个1“,接下来的数就是1211
1211被计为”一个1一个2两个1“接下来的数就是111221
给定一个正整数n,输出序列第n个元素。
输入
4
输出
1211
分析
题目不难,但是挺有趣的,直接模拟这个过程就可以得到结果。
代码
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
string getNext(const string &s)
{
stringstream ss;
for (auto i = s.begin(); i != s.end(); )
{
auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));
ss << distance(i, j) << *i;
i = j;
}
return ss.str();
}
int main()
{
int n;
cin >> n;
string s("1");
while (--n)
s = getNext(s);
cout << s << endl;
return 0;
}