【leetcode】Integer to Roman

时间:2023-03-09 03:23:01
【leetcode】Integer to Roman

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)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。(2)不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。(3)V 和 X 左边的小数字只能用Ⅰ。(4)L 和 C 左边的小数字只能用×。(5)D 和 M 左 边的小数字只能用 C 
利用贪心算法
 class Solution {
public:
string intToRoman(int num) { string result="";
string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[]= {,,,, , , , , , , , , }; int i=;
while(num!=)
{
while(num>=value[i])
{
num=num-value[i];
result+=symbol[i];
}
i++;
}
return result;
}
};