LintCode_420 报数

题目

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, ...

1 读作 "one 1" -> 11.

11 读作 "two 1s" -> 21.

21 读作 "one 2, then one 1" -> 1211.

C++代码

string countAndSay(int n) {
	// Write your code here
	string s1 = "1";
	string s2 = "";
	string s3 = "";
	int i;
	int j;
	for (i = 0; i < n; ++i)
	{
		int times = 0;
		char val = s1.front();
		for (j = 0; j < s1.size(); ++j)
		{
			s3 = "";
			if (val == s1[j]) times++;
			else
			{
				
				s3 = val + s3;
				s3 = (char)(times + '0') + s3;
				s2 += s3;
				s3 = "";
				val = s1[j];
				times = 1;
			}
		}
		s3 = val + s3;
		s3 = (char)(times + '0') + s3;
		s2 += s3;
		s1 = s2;
		s2 = "";
	}
	return s1;
}

  

posted @ 2016-05-02 11:50  红岸的电波  阅读(153)  评论(0)    收藏  举报