https://coding-prep.com/2023/05/16/zerojudge-a013-%e7%be%85%e9%a6%ac%e6%95%b8%e5%ad%97/
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000
#include <bits/stdc++.h>
using namespace std;
int f(char a){
if(a == 'I') return 1;
else if(a == 'V') return 5;
else if(a == 'X') return 10;
else if(a == 'L') return 50;
else if(a == 'C') return 100;
else if(a == 'D') return 500;
else if(a == 'M') return 1000;
return 0;
}
int romanToInt(string s) {
vector <int> a;
for(int i = 0;i < s.size();i++){
a.push_back(f(s[i]));
}
int sum = 0;
for(int i = 0;i < s.size();i++){
if(i < s.size() - 1 && a[i] < a[i+1]) sum -= a[i];
else sum += a[i];
}
return sum;
}
string intToRoman(int num) {
int val[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string ans[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int p = 0;
string res = "";
while(num) { // 直到被拿成 0 之前都繼續
int cnt = num / val[p]; // 計算它最多可以拿幾個
for(int i = 0;i < cnt;i++) {
res += ans[p];
}
num -= val[p] * cnt;
p++;
}
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';
}
}
vector 陣列
C++ std::vector 用法與範例
https://shengyu7697.github.io/std-vector/
自訂函式
自訂函式 | C++與演算法 (ntu.edu.tw)
int RomanToInt(string s) {
char d;
int sum=0;
for (char c : s) {
if (c=='M') {
if (d=='C') sum+=800;
else sum+=1000;
}
else if (c=='D') {
if (d=='C') sum+=300;
else sum+=500;
}
else if (c=='C') {
if (d=='X') sum+=80;
else sum+=100;
}
else if (c=='L') {
if (d=='X') sum+=50;
else sum+=30;
}
else if (c=='X') {
if (d=='I') sum+=8;
else sum+=10;
}
else if (c=='V') {
if (d=='I') sum+=3;
else sum+=5;
}
else if (c=='I') sum+=1;
d=c;
}
return sum;
}
link to http://course.tn.edu.tw/school.aspx?sch=213501 \
link to https://www.hcjh.tn.edu.tw/modules/tadnews/page.php?ncsn=17&nsn=3030
link to http://12basic.rcpet.edu.tw/ \
link to http://jhquery.tn.edu.tw/ \
link to https://tn.entry.edu.tw/ \
link to https://exam.tcte.edu.tw/teac_school/ _blanklink to http://humrig.tn.edu.tw/ \
link to https://www.jctv.ntut.edu.tw/u5/ _blanklink to https://exam.tcte.edu.tw/teac_school/ \
link to https://www.jctv.ntut.edu.tw/u5/ \