# ZeroJudge - a013: 羅馬數字 ### 題目連結:https://zerojudge.tw/ShowProblem?problemid=a013 ###### tags: `ZeroJudge` `模擬` ```cpp= #include <iostream> #include <string> #include <cmath> using namespace std; int romanValue[7] = { 1, 5, 10, 50, 100, 500, 1000 }, combineValue[13] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 }; string symbols = "IVXLCDM", combination[13] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; int FindSymbol(char letter) { for (int i = 0; i < 7; ++i) if (symbols[i] == letter) return i; return -1; } int RomanToArabic(string roman) { int arabic = 0, previous = 0, nowValue; for (int i = roman.size() - 1; i >= 0; --i) { nowValue = romanValue[FindSymbol(roman[i])]; arabic += (nowValue < previous ? -nowValue : nowValue); previous = nowValue; } return arabic; } string ArabicToRoman(int arabic) { string roman = ""; if (arabic == 0) return "ZERO"; for (int i = 12; i >= 0; --i) { while (arabic >= combineValue[i]) { arabic -= combineValue[i]; roman += combination[i]; } } return roman; } int main() { cin.sync_with_stdio(false); cin.tie(nullptr); string roman1, roman2; while (cin >> roman1 >> roman2, roman1 != "#") cout << ArabicToRoman(abs(RomanToArabic(roman1) - RomanToArabic(roman2))) << '\n'; } ```