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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
string solution = "";
string huns[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
while (num >= 1000) {
solution = solution + 'M';
num -= 1000;
}
solution = solution + huns[num/100]; num %= 100;
solution = solution + tens[num/10]; num %= 10;
solution = solution + ones[num];
return solution;
}
};
本文介绍了一种将整数转换为罗马数字的算法实现,适用于1到3999范围内的整数。通过定义千位、百位、十位和个位上的罗马数字表示,该算法能够高效地完成转换。
307

被折叠的 条评论
为什么被折叠?



