#12388: C++ AC 可參考


chris2012 (丁小魚)

學校 : 控江中学
編號 : 67347
來源 : [211.21.81.44]
最後登入時間 :
2019-03-05 12:55:39
a013. 羅馬數字 -- NPSC 模擬試題 | From: [118.166.233.63] | 發表日期 : 2017-07-20 16:21

#include <iostream>
#include <cstring>
using namespace std;

int TransNum(char a[]) ;     // 羅馬字轉數字函數
void TransRmnan(int Ans); // 數字轉羅馬字函數

int main() {

char a[30], b[30];

while (cin >> a) {
if ( a[0] == '#')
break;

cin >> b;

TransRmnan (abs(TransNum(a) - TransNum(b)));

cout << endl;

}
return 0;
}

//________________________________

int TransNum(char a[]) {

int Ans = 0;

for (int i = 0; i < strlen(a); i++) {

if (a[i] == a[i + 1] || a[i] == a[i - 1]) {
if (a[i] == 'M')
Ans += 1000;
if (a[i] == 'D')
Ans += 500;
if (a[i] == 'C')
Ans += 100;
if (a[i] == 'L')
Ans += 50;
if (a[i] == 'X')
Ans += 10;
if (a[i] == 'V')
Ans += 5;
if (a[i] == 'I')
Ans += 1;
}
else if (a[i] == 'C'&& a[i + 1] == 'M') { //六種減法組合
Ans += 900;
i++;
continue;
}
else if (a[i] == 'C'&& a[i + 1] == 'D') {
Ans += 400;
i++;
continue;
}
else if (a[i] == 'X'&& a[i + 1] == 'C') {
Ans += 90;
i++;
continue;
}
else if (a[i] == 'X'&& a[i + 1] == 'L') {
Ans += 40;
i++;
continue;
}
else if (a[i] == 'I'&& a[i + 1] == 'X') {
Ans += 9;
i++;
continue;
}
else if (a[i] == 'I'&& a[i + 1] == 'V') {
Ans += 4;
i++;
continue;
}
else {
if (a[i] == 'M')
Ans += 1000;
if (a[i] == 'D')
Ans += 500;
if (a[i] == 'C')
Ans += 100;
if (a[i] == 'L')
Ans += 50;
if (a[i] == 'X')
Ans += 10;
if (a[i] == 'V')
Ans += 5;
if (a[i] == 'I')
Ans += 1;
}

}
return Ans;
}

//---------------------------------------------------------------------------Output
void TransRmnan(int Ans) {

if (Ans / 1000 != 0)
for (int i = 0; i < Ans / 1000; i++)
cout << "M"; //---------- 千位

if ((Ans % 1000) / 100 == 9) //---------- 百位
cout << "CM";
if ((Ans % 1000) / 100 == 4)
cout << "CD";
if ((Ans % 1000) / 100 == 5)
cout << "D";

if ((Ans % 1000) / 100 == 1 || (Ans % 1000) / 100 == 2 || (Ans % 1000) / 100 == 3) {
for (int i = 0; i < (Ans % 1000) / 100; i++)
cout << "C";
}
if ((Ans % 1000) / 100 == 6 || (Ans % 1000) / 100 == 7 || (Ans % 1000) / 100 == 8) {
cout << "D";
for (int i = 0; i < (Ans % 1000) / 100 - 5; i++)
cout << "C";
}


if ((Ans % 100) / 10 == 9) //---------- 十位
cout << "XC";
if ((Ans % 100) / 10 == 4)
cout << "XL";
if ((Ans % 100) / 10 == 5)
cout << "L";

if ((Ans % 100) / 10 == 1 || (Ans % 100) / 10 == 2 || (Ans % 100) / 10 == 3) {
for (int i = 0; i < (Ans % 100) / 10; i++)
cout << "X";
}
if ((Ans % 100) / 10 == 6 || (Ans % 100) / 10 == 7 || (Ans % 100) / 10 == 8) {
cout << "L";
for (int i = 0; i < (Ans % 100) / 10 - 5; i++)
cout << "X";
}


if (Ans % 10 == 9) //---------- 個位
cout << "IX";
if (Ans % 10 == 4)
cout << "IV";
if (Ans % 10 == 5)
cout << "V";

if ((Ans % 10) == 1 || (Ans % 10) == 2 || (Ans % 10) == 3) {
for (int i = 0; i < Ans % 10; i++)
cout << "I";
}
if ((Ans % 10) == 6 || (Ans % 10) == 7 || (Ans % 10) == 8) {
cout << "V";
for (int i = 0; i < Ans % 10 - 5; i++)
cout << "I";
}

if (Ans == 0)
cout << "ZERO";
}

 
ZeroJudge Forum