#40762: 解答 c++


n0970616056@gmail.com (CIOU-HE-CHEN)

學校 : 不指定學校
編號 : 273811
來源 : [111.253.1.171]
最後登入時間 :
2024-06-14 11:55:43
a013. 羅馬數字 -- NPSC 模擬試題 | From: [27.247.62.93] | 發表日期 : 2024-06-11 22:14

#include <bits/stdc++.h> using namespace std; int romanToInt(const string& s) { unordered_map<char, int> roman = { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} }; int sum = 0; for (size_t i = 0; i < s.size(); ++i) { if (i < s.size() - 1 && roman[s[i]] < roman[s[i + 1]]) { sum -= roman[s[i]]; } else { sum += roman[s[i]]; } } return sum; } string intToRoman(int num) { vector<pair<int, string>> val = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} }; string res; for (const auto& [v, symbol] : val) { while (num >= v) { res += symbol; num -= v; } } return res; } int main() { string a, b; while (cin >> a) { if (a == "#") break; cin >> b; int na = romanToInt(a), nb = romanToInt(b); if (na == nb) { cout << "ZERO\n"; } else { cout << intToRoman(abs(na - nb)) << '\n'; } } return 0; }

 
ZeroJudge Forum