Skip to content

Instantly share code, notes, and snippets.

@pinglunliao
Last active November 5, 2019 08:27
Show Gist options
  • Save pinglunliao/d49f8fc6cccecb821fbe to your computer and use it in GitHub Desktop.
Save pinglunliao/d49f8fc6cccecb821fbe to your computer and use it in GitHub Desktop.
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment