【问题描述】
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Example: Input:11 Output:XI
问题来源:Integer to Roman
【问题解析】
由于问题给出的整数范围是1~3999,只考虑到最大的单位M。将Roman数字表几个关键的对应的阿拉伯数字对应:
I:1
IV:4
V:5
IX:9
X:10
XL:40
L:50
XC:90
C:100
CD:400
D:500
CM:900
M:1000
类似于I,X,C这种可以表示在比它大的Roman数字的前面,每两个数会有一个减法的表示,例如IV。
每次使用贪心方法表示最大的数字,例如:455,CD,L,V,455->CDLV。
【源代码】
class Solution {
public:
string intToRoman(int num) {
string s;
string numeral[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
for (int i = 0; num != 0; i++) {
while (num >= value[i]) {
num -= value[i];
s += numeral[i];
}
}
return s;
}
};