From : https://leetcode.com/problems/integer-to-roman/
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
string intToRoman(int num) {
if(num<1 || num >3999) return "";
string ans;
int cnt, i=0;// i odd:1** even:5**
map<int, char> base;
base[1]='I';
base[5] = 'V';
base[10] = 'X';
base[50] = 'L';
base[100] = 'C';
base[500] = 'D';
base[1000] = 'M';
for(map<int, char>::reverse_iterator it=base.rbegin(); it!=base.rend(); it++) {
i++;
if(num/it->first) {
cnt = num/it->first;
num -= cnt*it->first;
if(i%2==1&&cnt==4) {
ans += it->second;
it--;
ans += it->second;
it++;
cnt = 0;
} else if(i%2==0&&cnt==1&&(num+it->first/5)/it->first==1) {
num -= 4*it->first/5;
it++;
ans += it->second;
it--;it--;
ans += it->second;
it++;
cnt = 0;
}
char ch = it->second;
while(cnt--) {
ans += ch;
}
}
}
return ans;
}
};
class Solution {
public:
string intToRoman(int num) {
if(num<1 || num >3999) return "";
string ans;
int bases[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string values[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
for(int i=0; i<13; i++) {
while(num >= bases[i]) {
num -= bases[i];
ans += values[i];
}
}
return ans;
}
};