Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Personal Tips: 使用map,记录1,5,10,50,100,500,1000分别对应的罗马数字,以及其规则。代码如下:
class Solution
{
public:
Solution()
{
RomanTable.insert(pair<int, char>(1, 'I'));
RomanTable.insert(pair<int, char>(5, 'V'));
RomanTable.insert(pair<int, char>(10, 'X'));
RomanTable.insert(pair<int, char>(50, 'L'));
RomanTable.insert(pair<int, char>(100, 'C'));
RomanTable.insert(pair<int, char>(500, 'D'));
RomanTable.insert(pair<int, char>(1000, 'M'));
}
string intToRoman(int num) {
string Roman;
int count = 1000;
while (count>0)
{
Roman.append(getSingleNum(num / count, count));
num -= (num / count)*count;
count /= 10;
}
return Roman;
}
inline string getSingleNum(int num, int count) {
string singleRoman;
if (num<4) return singleRoman.append(num, RomanTable[count]);
else if (num <= 5)
{
singleRoman.append(5 - num, RomanTable[count]);
singleRoman.append(1, RomanTable[5 * count]);
}
else if (num<9)
{
singleRoman.append(1, RomanTable[5 * count]);
singleRoman.append(num - 5, RomanTable[count]);
}
else if (num == 9)
{
singleRoman.append(1, RomanTable[count]);
singleRoman.append(1, RomanTable[10 * count]);
}
return singleRoman;
}
private:
map<int, char> RomanTable;
};