Description:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
首先得明白Roman数字构成,具体下图所示,这里需要注意一个点,下面举例来说明:
- 阿拉伯数字4 对应的罗马数字 IV
- 阿拉伯数字9 对应的罗马数字 IX
- 阿拉伯数字40 对应的罗马数字 XL
- 阿拉伯数字90 对应的罗马数字 XC
- 阿拉伯数字400 对应的罗马数字 CD
- .......是不是找到int2roman的规律了???
算法思想:
步骤1. 建立对应表,根据上面阐述的Int2Roman的规律,本道题roman数字表达最大是 M,最小是 I
步骤2. 依次计算roman数字有多少个,即会有多少个M,多少个CM,多少个D。详见代码。
代码如下:
class Solution {
public:
string intToRoman(int num) {
string ans = "";
int buf[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string roman[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV","I"};
int idx = 0;
int count;
while(num > 0) {
count = num / buf[idx];
while(count --)
ans += roman[idx];
num = num % buf[idx];
idx ++;
}
return ans;
}
};