24h購物| | PChome| 登入
2012-11-01 20:49:21| 人氣436| 回應0 | 上一篇 | 下一篇

[UVA] 759 - The Return of the Roman Empire

推薦 0 收藏 0 轉貼0 訂閱站台

  The Return of the Roman Empire 

Input and Output 

Write a program that accepts Roman numerals (one per line) and converts them to decimal form.


Remember, I=1, V=5, X=10, L=50, C=100, D=500, and M=1000. Furthermore, there are the following digraphs: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900.


The program should reject improperly formed numerals.

Sample Input 

MCMXCVIII
CCM

Sample Output 

1998
This is not a valid number

我被 4000 整了, 羅馬數字沒有包函 4000

#include <stdio.h>
#include <iostream>
#include <map>
using namespace std;

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;
    char *str, in[50];
    map<string, int> ch1;
    for(n = 1; n < 4000; n++) {
        str = toRoman(n);
        ch1[str] = n;
        delete[] str;
    }
    while(gets(in)) {
        if(in[0] == '\0')
            puts("0");
        else if(ch1[in] == 0)
            cout << "This is not a valid number" << endl;
        else
            cout << ch1[in] << endl;
    }
    return 0;
}

台長: Morris
人氣(436) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[ACM-ICPC] 4712 - Airplane Parking
此分類上一篇:[UVA] 10895 - Matrix Transpose

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文