Integer to Roman Conversion
Integer to Roman Conversion
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Process Each Digit Then Reverse
string intToRoman(int num) {
vector<int> sym = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
string res;
int i=-2;
for(int j=0;j<3;++j) {
i+=2;
int n=num%10;
if (n==5) {
res.push_back(sym[i+1]);
} else if (n>5) {
if (n == 9) {
res.push_back(sym[i+2]);
res.push_back(sym[i]);
} else {
n-=5;
for(int j=0;j<n;++j) res.push_back(sym[i]);
res.push_back(sym[i+1]);
}
} else {
if (n==4) {
res.push_back(sym[i+1]);
res.push_back(sym[i]);
} else {
for(int j=0;j<n;++j) res.push_back(sym[i]);
}
}
num/=10;
}
while(num--) res.push_back('M');
reverse(res.begin(), res.end());
return res;
}Enumerate Using Problem Constraints
string intToRoman(int num) {
string romanPieces[]={"","I","II","III","IV","V","VI","VII","VIII","IX",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","M","MM","MMM","MMMM"};
return romanPieces[num/1000+30]+romanPieces[(num/100)%10+20]
+romanPieces[(num/10)%10+10]+romanPieces[num%10];
}Key Insights
- We can observe the problem’s constraints and enumerate all possibilities to trade space for time efficiency.
#enumeration #math