summaryrefslogtreecommitdiff
path: root/25.c
blob: b0f729358531f9bae0ed1734684408142d52acf2 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>


// Only works for positive numbers so far!
char *
snafu(char * dest, size_t len, long n)
{
	size_t i = 0, j;

	// Build string in reverse.
	while (n && i < len) {
		int d = n % 5;

		switch (d) {
		case 0:
		case 1:
		case 2:
			dest[i++] = '0' + d;
			break;

		case 3:
			dest[i++] = '=';
			n += 5;
			break;

		case 4:
			dest[i++] = '-';
			n += 5;
			break;
		}

		n /= 5;
	}

	dest[i] = '\0';

	// Reverse string to be right way around
	for (j = 0; j < i / 2; ++j) {
		char tmp = dest[j];
		dest[j] = dest[i - 1 - j];
		dest[i - 1 - j] = tmp;
	}

	return dest;
}


int
main()
{
	long i = 0, total = 0;
	int c;
	char buf[BUFSIZ];

	while ((c = fgetc(stdin)) != EOF) {
		switch (c) {
		case '2':
			i *= 5;
			i += 2;
			break;

		case '1':
			i *= 5;
			i += 1;
			break;

		case '0':
			i *= 5;
			break;

		case '-':
			i *= 5;
			i -= 1;
			break;

		case '=':
			i *= 5;
			i -= 2;
			break;

		case '\n':
#if 0
			fprintf(stderr, "%s (%ld)\n", snafu(buf, sizeof(buf), i), i);
#endif
			total += i;
			i = 0;
			break;

		default:
			fprintf(stderr, "Unexpected input: %c\n", c);
			return -1;
		}
	}

	printf("Total: %s (%ld)\n", snafu(buf, sizeof(buf), total), total);

	return 0;
}