Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
题目本身很简单 就是给一个1到3999的数字 转换成IVXLCDM这几个字母的罗马字符串。 但是 一个数字可以拆成的组合非常多,可以有很多种合理的组合,这里经过一次提交发现题目中对于4,40,400的表示应该是5-1,50-10,500-100, 对于9,99,999的表示应该是IX,XC,CM 那就直接做一个映射表好了 ,其他的数字都累加 比如1,2,3就分别是1个I,2个I,3个I ,因为他们小于5, 对于大于5的,就先输出5所对应的的V再输入一个I,两个I,三个I。
class Solution {
public:
string intToRoman(int num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
string result;
if (num == 0) return result;
int divisor = 1000, repeat = 0;
while (num > 0)
{
repeat = num / divisor;
if (repeat == 4 || repeat == 5 || repeat == 9)
{
result += mapInt(repeat * divisor);
repeat = 0;
}
if (repeat > 5)
{
result += mapInt(5 * divisor);
repeat -= 5;
}
while (repeat)
{
result += mapInt(divisor);
--repeat;
}
num %= divisor;
divisor /= 10;
}
return result;
}
private:
string mapInt(int integer)
{
switch (integer)
{
case 1: return "I";
case 4: return "IV";
case 5: return "V";
case 9: return "IX";
case 10: return "X";
case 40: return "XL";
case 50: return "L";
case 90: return "XC";
case 100: return "C";
case 400: return "CD";
case 500: return "D";
case 900: return "CM";
case 1000: return "M";
}
}
};