若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
這題用查表法,先將兩個羅馬數字(a, b)轉成一般數字(c, d)後,算出 c 與 d 差的絕對值 e。再將 e 換成羅馬數字。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
short number(char c) | |
{ | |
short num; | |
switch(c) | |
{ | |
case 'I': | |
num = 1; | |
break; | |
case 'V': | |
num = 5; | |
break; | |
case 'X': | |
num = 10; | |
break; | |
case 'L': | |
num = 50; | |
break; | |
case 'C': | |
num = 100; | |
break; | |
case 'D': | |
num = 500; | |
break; | |
case 'M': | |
num = 1000; | |
break; | |
default: | |
num = 0; | |
break; | |
} | |
return num; | |
} | |
short getValue(const string& s ) | |
{ | |
short preValue = 1000, curValue, value = 0; | |
short len = s.length(); | |
for( int i = 0; i < len; i++ ) | |
{ | |
curValue = number(s[i]); | |
value += curValue; | |
if( curValue > preValue ) | |
value -= 2 * preValue; | |
preValue = curValue; | |
} | |
return value; | |
} | |
void attachMsg(short check, string &result, string msg) | |
{ | |
if( check == 9 ) | |
{ | |
result.append(msg.substr(2,1)); | |
result.append(msg.substr(0,1)); | |
check = 0; | |
} | |
if( check == 4 ) | |
{ | |
result.append(msg.substr(2,1)); | |
result.append(msg.substr(1,1)); | |
check = 0; | |
} | |
if( check >= 5 ) | |
{ | |
result.append(msg.substr(1,1)); | |
check -= 5; | |
} | |
for(int i = 0; i < check; i++) | |
{ | |
result.append(msg.substr(2,1)); | |
} | |
} | |
void prtNum( short n ) | |
{ | |
string result; | |
n = (n < 0 ? -n: n); | |
short check = n / 1000; | |
for(int i = 0; i < check; i++) | |
result.append("M"); | |
n = n % 1000; | |
check = n / 100; | |
attachMsg(check, result, "MDC"); | |
n = n % 100; | |
check = n / 10; | |
attachMsg(check, result, "CLX"); | |
n = n % 10; | |
check = n; | |
attachMsg(check, result, "XVI"); | |
cout << result; | |
} | |
int main() | |
{ | |
string a, b; | |
short numA, numB, numDif; | |
while( cin >> a ) | |
{ | |
if( a[0] == '#' ) | |
break; | |
cin >> b; | |
numA = getValue(a); | |
numB = getValue(b); | |
numDif = numA - numB; | |
if( numDif != 0 ) | |
prtNum(numDif); | |
else | |
cout << "ZERO"; | |
cout << endl; | |
} | |
return 0; | |
} |
沒有留言:
張貼留言