#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct numeral {
const char * name;
int factor;
int summand;
};
struct numeral words[] =
{
{ "zero", 1, 0 },
{ "one", 1, 1 },
{ "two", 1, 2 },
{ "three", 1, 3 },
{ "four", 1, 4 },
{ "five", 1, 5 },
{ "six", 1, 6 },
{ "seven", 1, 7 },
{ "eight", 1, 8 },
{ "nine", 1, 9 },
{ "ten", 1, 10 },
{ "eleven", 1, 11 },
{ "twelve", 1, 12 },
{ "thirteen", 1, 13 },
{ "fourteen", 1, 14 },
{ "fiveteen", 1, 15 },
{ "sixteen", 1, 16 },
{ "seventeen", 1, 17 },
{ "eightteen", 1, 18 },
{ "nineteen", 1, 19 },
{ "twenty", 1, 20 },
{ "thirty", 1, 30 },
{ "fourty", 1, 40 },
{ "fifty", 1, 50 },
{ "sixty", 1, 60 },
{ "seventy", 1, 70 },
{ "eighty", 1, 80 },
{ "ninety", 1, 90 },
{ "hundred", -1, -1 },
{ "thousand", 1000, 0 },
{ NULL, 0, 0}
};
static int cmp(const void * const ptr_a, const void * const ptr_b)
{
const struct numeral * const a = ptr_a;
const struct numeral * const b = ptr_b;
return strcmp(a->name, b->name);
}
void sort_numeral(void)
{
const size_t words_sz = sizeof(words);
const size_t element_sz = sizeof(words[0]);
const size_t words_len = (words_sz / element_sz) - 1;
qsort(words, words_len, element_sz, cmp);
}
const struct numeral * find_numeral(const char * const str)
{
const int words_sz = sizeof(words);
const int element_sz = sizeof(words[0]);
int start = 0;
int len = (words_sz / element_sz) - 1;
while (len > 0) {
const int step = len / 2;
const int middle = start + step;
const int is_less = strcmp(words[middle].name, str) < 0;
if (is_less) {
start = middle + 1;
len -= step + 1;
} else {
len = step;
}
}
return words + start;
}
void print_num(const char * line)
{
int64_t value = 0;
for (;;) {
char * str = NULL;
int pos;
const int len = sscanf(line, "%ms%n", &str, &pos);
if (len == EOF || str == NULL) break;
line += pos;
const struct numeral * const numeral = find_numeral(str);
const int is_ok = numeral->name && strcmp(numeral->name, str) == 0;
if (str != NULL) free(str);
if (!is_ok) {
printf("Illegal!\n");
return;
}
if (numeral->factor != -1) {
value = value * numeral->factor + numeral->summand;
} else {
const int digit = value % 10;
value -= digit;
value += 100 * digit;
}
}
printf("%ld\n", value);
}
int main()
{
sort_numeral();
char * line = NULL;
size_t line_sz = 0;
for (;;) {
ssize_t len = getline(&line, &line_sz, stdin);
if (len == -1 || strcmp(line, "quit\n") == 0) break;
print_num(line);
}
if (line != NULL) free(line);
}