/
1078.c
58 lines (51 loc) · 1.15 KB
/
1078.c
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
#include <stdio.h>
void compress()
{
char previous = getchar(), current;
int count = 1;
while ((current = getchar())) {
if (current == previous) {
count++; /* Increament count */
} else {
if (count > 1) /* Only print if count > 1 */
printf("%d", count);
putchar(previous);
previous = current;
count = 1;
}
if (current == '\n' || current == EOF) /* Don't put this in while () */
break;
}
}
void decompress()
{
char c;
int count = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (c >= '0' && c <= '9') { /* If it is number */
count = count * 10 + c - '0'; /* Accumulate count */
} else { /* If it is not number */
if (count == 0) /* No number before char */
count = 1; /* print once */
for (int i = 0; i < count; i++) /* Or print 'count' times */
putchar(c);
count = 0; /* Reset 'count' */
}
}
}
int main()
{
switch(getchar()) {
case 'C':
while (getchar() != '\n');
compress();
break;
case 'D':
while (getchar() != '\n');
decompress();
break;
default:
break;
}
return 0;
}