一個是把羅馬數字變成阿拉伯數字,
另外一個是把阿拉伯數字變成羅馬數字。
羅馬數字變成阿拉伯數字就是,
遇到其羅馬字母就將結果加上其代表數值,
再判斷它前一個字母是不是小於它,
如果是就減掉前面那個小於它的值的兩倍。
(因為你在前面執行到它的時候有加的它的值,所以不僅要把多的去掉,
還要把它原本減一次的意思表示出來,導致要扣兩倍。)
P.S. 根據羅馬數字的規則,會有這種狀況的只有:IV、IX、XL、XC、CD、CM。
而把阿拉伯數字變成羅馬數字就以
M、CM、D、CD、C、XC、L、XL、X、IX、V、IV、I
這個順序把大於它的值一直減掉,然後一直輸出,即可得解。
[C++](4ms, 740KB)
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; | |
int roman_to_number( string s ) | |
{ | |
int output = 0; | |
for( int i = 0 ; i < s.length() ; i++) | |
{ | |
switch( s[i] ) | |
{ | |
case 'I': | |
output++; | |
break; | |
case 'V': | |
output += 5; | |
if( s[i-1] == 'I' ) | |
output -= 2; | |
break; | |
case 'X': | |
output += 10; | |
if( s[i-1] == 'I' ) | |
output -= 2; | |
break; | |
case 'L': | |
output += 50; | |
if( s[i-1] == 'X' ) | |
output -= 20; | |
break; | |
case 'C': | |
output += 100; | |
if( s[i-1] == 'X' ) | |
output -= 20; | |
break; | |
case 'D': | |
output += 500; | |
if( s[i-1] == 'C' ) | |
output -= 200; | |
break; | |
case 'M': | |
output += 1000; | |
if( s[i-1] == 'C' ) | |
output -= 200; | |
break; | |
} | |
} | |
return output; | |
} | |
string number_to_roman( int i ) | |
{ | |
string output = ""; | |
if( i == 0 ) | |
return (output = "ZERO"); | |
int temp; | |
while( i > 0 ) | |
{ | |
if( i >= 1000 ) | |
{ | |
i -= 1000; | |
output += "M"; | |
} | |
else if( i >= 900 ) | |
{ | |
i -= 900; | |
output += "CM"; | |
} | |
else if( i >= 500 ) | |
{ | |
i -= 500; | |
output += "D"; | |
} | |
else if( i >= 400 ) | |
{ | |
i -= 400; | |
output += "CD"; | |
} | |
else if( i >= 100 ) | |
{ | |
i -= 100; | |
output += "C"; | |
} | |
else if( i >= 90 ) | |
{ | |
i -= 90; | |
output += "XC"; | |
} | |
else if( i >= 50 ) | |
{ | |
i -= 50; | |
output += "L"; | |
} | |
else if( i >= 40 ) | |
{ | |
i -= 40; | |
output += "XL"; | |
} | |
else if( i >= 10 ) | |
{ | |
i -= 10; | |
output += "X"; | |
} | |
else if( i >= 9 ) | |
{ | |
i -= 9; | |
output += "IX"; | |
} | |
else if( i >= 5 ) | |
{ | |
i -= 5; | |
output += "V"; | |
} | |
else if( i >= 4 ) | |
{ | |
i -= 4; | |
output += "IV"; | |
} | |
else | |
{ | |
i -= 1; | |
output += "I"; | |
} | |
} | |
return output; | |
} | |
int main() | |
{ | |
string num1, num2; | |
while( cin >> num1 ) | |
{ | |
if( num1 == "#" ) | |
break; | |
cin >> num2; | |
cout << number_to_roman( abs( roman_to_number( num1 ) - roman_to_number( num2 ) ) ) << endl; | |
} | |
return 0; | |
} |
1 意見:
學長安安,可以問一下,為什麼不用#include cmath(or math.h)阿?
張貼留言