首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

Integer to Roman (罗马数字变换) 【leetcode】

2013-09-24 
Integer to Roman (罗马数字转换) 【leetcode】题目:Given an integer, convert it to a roman numeral.Inpu

Integer to Roman (罗马数字转换) 【leetcode】

题目:Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

科普了一下表达方式,理解了就不复杂了。

I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;

其中每两个阶段的之间有一个减法的表示,比如900=CM, C写在M前面表示M-C。

范围给到3999,感觉情况不多直接打表其实更快,用代码判断表示估计比较繁琐。

然后就是贪心的做法,每次选择能表示的最大值,把对应的字符串连起来。 



class Solution {public:    string intToRoman(int num) {        string str;          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];                str+=symbol[i];            }        }        return str;    }};


热点排行