题目链接:Integer to Roman
- 题目描述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
(1)思路:和上次那个Roman to Integer 一样,需要先搞清楚罗马字母的表示方法。然后用贪心算法,每次选择数字中能表达的最大值。
(2)代码:
class Solution {
public:
string intToRoman(int num) {
string ans;
string symbol[] = {"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];
ans += symbol[i];
}
}
return ans;
}
};