一、C++代码:
string intToRoman(int num) {
map<int, char> mapRoman = { {1,'I'},{5,'V'},{10,'X'},{50,'L'},{100,'C'},
{500,'D'},{1000,'M'} };
int temp = 0;
int type;
string res;
for (int i = 3; i >= 0; i--) {
type = pow(10, i);
num = num - temp * type * 10;
temp = num / type;
if (temp == 4) {
res.push_back(mapRoman.find(type)->second);
res.push_back(mapRoman.find(type * 5)->second);
}
else if (temp == 9) {
res.push_back(mapRoman.find(type)->second);
res.push_back(mapRoman.find(type * 10)->second);
}
else if (temp > 4) {
res.push_back(mapRoman.find(type * 5)->second);
int temp1 = temp - 5;
while (temp1-- > 0)
res.push_back(mapRoman.find(type)->second);
}
else {
int temp1 = temp;
while (temp1-- > 0)
res.push_back(mapRoman.find(type)->second);
}
}
return res;
}