-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_and_say.cpp
More file actions
68 lines (60 loc) · 1.42 KB
/
count_and_say.cpp
File metadata and controls
68 lines (60 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* =====================================================================================
*
* Filename: count_and_say.cpp
*
* Description: 38. Count and Say: Given an integer n, generate the nth term of the
* count-and-say sequence.
*
* Version: 1.0
* Created: 09/13/18 01:25:26
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
class Solution
{
public:
std::string countAndSay(int n)
{
if (n < 1 || n > 30)
{
return "";
}
else if (n == 1)
{
return "1";
}
std::string last = countAndSay(n - 1);
std::string curr;
for (size_t i = 0; i < last.size(); i++)
{
int count = 1;
while ((i + 1 < last.size()) && (last[i] == last[i + 1]))
{
i++;
count++;
}
curr += std::to_string(count) + last[i];
}
return curr;
}
};
int main(int argc, char* argv[])
{
int num = 3;
if (argc > 1)
{
num = atoi(argv[1]);
}
std::string str = Solution().countAndSay(num);
printf("%d -> %s\n", num, str.c_str());
return 0;
}