From 55b3435579ba4982a8cb7f4aacb3d7fa704c2e93 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Mon, 2 Oct 2017 09:16:28 +0800 Subject: [PATCH] Count and say Signed-off-by: Leo Ma --- 038_count_and_say/Makefile | 2 + 038_count_and_say/count_and_say.c | 75 +++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 038_count_and_say/Makefile create mode 100644 038_count_and_say/count_and_say.c diff --git a/038_count_and_say/Makefile b/038_count_and_say/Makefile new file mode 100644 index 0000000..27b8e9a --- /dev/null +++ b/038_count_and_say/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test count_and_say.c diff --git a/038_count_and_say/count_and_say.c b/038_count_and_say/count_and_say.c new file mode 100644 index 0000000..7dca81b --- /dev/null +++ b/038_count_and_say/count_and_say.c @@ -0,0 +1,75 @@ +#include +#include +#include + +static void parse(char *input, char *output) +{ + char *p = input; + char *q = output; + + while (*p != '\0') { + int count = 1; + while (p[0] == p[1]) { + count++; + p++; + } + + /* reverse number */ + int n = 0; + while (count > 0) { + n += count % 10; + count /= 10; + } + + /* parse count */ + while (n > 0) { + *q++ = (n % 10) + '0'; + n /= 10; + } + + *q++ = p[0]; + p++; + } + + *q = '\0'; +} + +static char *countAndSay(int n) +{ + if (n < 1) { + return NULL; + } + + char *result; + char *prev = malloc(10000); + char *next = malloc(10000); + strcpy(prev, "1"); + + if (n == 1) { + return prev; + } + + int i; + for (i = 2; i <= n; i++) { + if (i & 0x1) { + parse(next, prev); + result = prev; + } else { + parse(prev, next); + result = next; + } + } + + return result; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%s\n", countAndSay(atoi(argv[1]))); + return 0; +}