2013-02-27 10:21:57Morris

[UVA][羅馬數字] 12397 - Roman Numerals

Problem A: Roman Numerals

We would like to build Roman numerals with matches. As you know, Roman numerals are based on the following seven characters: I, V, X, L, C, D, M. Here we introduce the LUSIVERS font, in which the respective characters look like this:

Write a program that counts the number of matches used to build Roman numerals in the LUSIVERS font. This number is exactly the total number of "match heads" in the characters. For instance, to make the number 14 (=XIV), five matches are used.

You must follow the "standard modern Roman numerals" (as shown on the Wikipedia page). Expressions like IC or IIII are not allowed.

Input

Input contains multiple lines, each giving a value of N (1 ≤ N ≤ 3999).

Output

For each test case, output the number of matches required to build the number N in Roman numerals.

Sample Input

14
2011

Sample Output

5
11

Problemsetter: Mak Yan Kei
The LUSIVERS font is available on FontSpace as a freeware

#include <stdio.h>
char* toRoman(int num) {
    const char rcode[13][3] = {"M", "CM", "D", "CD", "C", "XC", "L",
                        "XL", "X", "IX", "V", "IV", "I"};
    const int val[13] = {1000, 900, 500, 400, 100, 90, 50,
                        40, 10, 9, 5, 4, 1};
    char *roman = new char[30], idx = 0;
    int i;
    for(i = 0; i < 13; i++) {
        while(num >= val[i]) {
            num -= val[i];
            roman[idx++] = rcode[i][0];
            if(rcode[i][1] != '\0')
                roman[idx++] = rcode[i][1];
        }
    }
    roman[idx] = '\0';
    return roman;
}
int main() {
    int n, i;
    char cost[128] = {};
    cost['I'] = 1;
    cost['V'] = 2;
    cost['X'] = 2;
    cost['L'] = 2;
    cost['C'] = 2;
    cost['D'] = 3;
    cost['M'] = 4;
    while(scanf("%d", &n) == 1) {
        char *p = toRoman(n);
        n = 0;
        for(i = 0; p[i]; i++)
            n += cost[p[i]];
        printf("%d\n", n);
        delete[] p;
    }
}