首页 > 代码库 > 【leetcode】Integer to Roman

【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 
利用贪心算法
 
 1 class Solution { 2 public: 3     string intToRoman(int num) { 4         5         string result=""; 6         string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};     7         int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1}; 8         9         int i=0;10         while(num!=0)11         {12             while(num>=value[i])13             {14                 num=num-value[i];15                 result+=symbol[i];16             }17             i++;18         }19         return result;20     }21 };

 

【leetcode】Integer to Roman