Skip to content

Instantly share code, notes, and snippets.

@mingtsay
Last active December 18, 2015 22:48
Show Gist options
  • Save mingtsay/5856543 to your computer and use it in GitHub Desktop.
Save mingtsay/5856543 to your computer and use it in GitHub Desktop.
#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); // string 轉成阿拉伯數字
int to_arabic(char c); // char 轉成阿拉伯數字
string to_roman(int t); //阿拉伯數字轉成 string
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]; // 如果前面比後面小就要扣掉,例如 IV 是 5 - 1 = 4
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) // 依照題目要求,如果是零就輸出 ZERO
return "ZERO";
string tmp;
for(int j = 0; j < N; j += 2) // 依照羅馬數字的每個位數來轉換
{
int k = t / arabic[j]; // 和其他進位制一樣用除法
// 處理羅馬數字特殊規定
if(k == 9) // 9 = 10 - 1 => IX
tmp.push_back(roman[j]), tmp.push_back(roman[j-2]);
else if(k == 4) // 4 = 5 - 1 => IV
tmp.push_back(roman[j]), tmp.push_back(roman[j-1]);
else
{
if(k > 4) // 大於 5 但小於 10 要合併成羅馬數字 V (十進位是5)
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment