版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sd4567855/article/details/86776985
day32, 报数
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
-
1
-
11
-
21
-
1211
-
111221
1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: “1”
示例 2:
输入: 4
输出: “1211”
解答:这道题坑的一点,在于如何处理替换后字符串的当前位置。解决方法是创建一个新的string用来存储。
代码:
string countAndSay(int n) {
if( n == 0)
return "";
string res = "1", result = "";
while( --n){
for( int i = 0; i < res.size(); ){
int sum = 1;
int j = i + 1;
for( ; j < res.size() && res[j - 1] == res[ j]; j++)
sum++;
char c1 = sum + '0', c2 = res[ j - 1];
result += c1, result += c2;
i = j;
}
res = result;
result.clear();
}
return res;
}
运行结果: