Skip to content

Instantly share code, notes, and snippets.

@safeng
Last active December 28, 2015 09:29
Show Gist options
  • Save safeng/7479534 to your computer and use it in GitHub Desktop.
Save safeng/7479534 to your computer and use it in GitHub Desktop.
Given an integer, convert it to a roman numeral.
class Solution {
public:
string intToRoman(int num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
/*Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
*/
static int tb[7] = {1,5,10,50,100,500,1000};
static char sym[7] = {'I','V','X','L','C','D','M'};
ostringstream oss;
int curUnit = 6;
while(curUnit>=0 && num)
{
// special cases
switch (curUnit)
{
case 5: // 500
if(num/900 == 1)
{
oss<<"CM";
num-=900;
}
break;
case 4: // 100
if(num/400 == 1)
{
oss <<"CD";
num-=400;
}
break;
case 3: // 50
if(num/90 == 1)
{
oss<<"XC";
num-=90;
}
break;
case 2: // 10
if(num/40 == 1)
{
oss<<"XL";
num-=40;
}
break;
case 1: // 5
if(num/9 == 1)
{
oss<<"IX";
num-=9;
}
break;
case 0: // 1
if(num/4 == 1)
{
oss<<"IV";
num-=4;
}
break;
}
int count = num/tb[curUnit];
for(int i = 0; i<count; ++i)
{
oss << sym[curUnit];
}
num = num - count*tb[curUnit];
curUnit--;
}
return oss.str();
}
};
class Solution {
public:
int romanToInt(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
/*Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
*/
/*static int tb[7] = {1,5,10,50,100,500,1000};
static char sym[7] = {'I','V','X','L','C','D','M'};
static int spec[6] = {4,9,40,90,400,900};
static string specStr[6] = {"IV","IX","XL","XC","CD","CM"};*/
int num = 0;
for(size_t i = 0; i<s.length(); ++i)
{
char c = s[i];
switch (c)
{
case 'M':
num += 1000;
break;
case 'D':
num += 500;
break;
case 'C':
// look ahead
if(i+1 < s.length())
{
if(s[i+1] == 'M')
{
num +=900;
i++;
}else if(s[i+1] == 'D')
{
num += 400;
i++;
}else
{
num += 100;
}
}else
{
num += 100;
}
break;
case 'L':
num+=50;
break;
case 'X':
// look ahead
if(i+1 < s.length())
{
if(s[i+1] == 'C')
{
num+=90;
i++;
}else if(s[i+1] == 'L')
{
num+=40;
i++;
}else
{
num+=10;
}
}else
{
num+=10;
}
break;
case 'V':
num+=5;
break;
case 'I':
// look ahead
if(i+1 < s.length())
{
if(s[i+1] == 'X')
{
num+=9;
i++;
}else if(s[i+1] == 'V')
{
num+=4;
i++;
}else
{
num++;
}
}else
{
num++;
}
break;
}
}
return num;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment