-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc22.c
More file actions
46 lines (40 loc) · 922 Bytes
/
c22.c
File metadata and controls
46 lines (40 loc) · 922 Bytes
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
// Count and say problem
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* countAndSay(int n)
{
if (n == 1)
{
char* base = (char*)malloc(2);
strcpy(base, "1");
return base;
}
char* prev = countAndSay(n - 1);
int len = strlen(prev);
char* result = (char*)malloc(len * 2 + 1); // Safe buffer
int index = 0;
for (int i = 0; i < len;)
{
char digit = prev[i];
int count = 0;
while (i < len && prev[i] == digit)
{
count++;
i++;
}
result[index++] = count + '0'; // convert int to char
result[index++] = digit;
}
result[index] = '\0';
free(prev); // free memory from previous call
return result;
}
int main()
{
int n = 5;
char* output = countAndSay(n);
printf("Count and Say term %d: %s\n", n, output);
free(output);
return 0;
}