想看題目請點我
// Zero: a013 - 羅馬數字
// 2008.07.18 Celia
// Result: AC
// Time: 26ms
// Note: NPSC practice
#include <iostream>
#include <string>
#define N 7
using namespace std;
char roman[N] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
int arabic[N] = {1000, 500, 100, 50, 10, 5, 1};
int iabs(const int& t);
int to_arabic(string t);
int to_arabic(char c);
string to_roman(int t);
int main()
{
for(;;)
{
string t1, t2;
cin >> t1;
if(t1[0] == '#')
break;
else
cin >> t2;
cout << to_roman(iabs(to_arabic(t1) - to_arabic(t2))) << endl;
}
return 0;
}
inline int iabs(const int& t)
{
return (t > 0)? t : -t;
}
inline int to_arabic(string t)
{
int len = t.length(), array[len];
for(int i = 0; i < len; i++)
array[i] = to_arabic(t[i]);
len--;
int tmp = array[len];
for(int i = 0; i < len; i++)
{
if(array[i] < array[i+1])
tmp -= array[i];
else
tmp += array[i];
}
return tmp;
}
inline int to_arabic(char c)
{
for(int i = 0; i < N; i++)
if(c == roman[i])
return arabic[i];
}
inline string to_roman(int t)
{
if(t == 0)
return "ZERO";
string tmp;
for(int j = 0; j < N; j += 2)
{
int k = t / arabic[j];
if(k == 9)
tmp.push_back(roman[j]), tmp.push_back(roman[j-2]);
else if(k == 4)
tmp.push_back(roman[j]), tmp.push_back(roman[j-1]);
else
{
if(k > 4)
tmp.push_back(roman[j-1]), k -= 5;
for(int i = k; i > 0; i--)
tmp.push_back(roman[j]);
}
t %= arabic[j];
}
return tmp;
}這題我好懶的自己寫 ,(摳鼻
記得當初寫1~100羅馬我寫的好多行 ,
所以這次剛好看到類似的題目 ,
就上網找比我寫的好的程式 ,
大家跟我就一起研讀高手寫的吧 :D