您的位置:首页 > 其它

LeedCode Integer to Roman

2017-10-21 10:18 323 查看
网址:https://leetcode.com/problems/integer-to-roman/description/

题目:

   Given an integer, convert it to a roman numeral.

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

翻译:

   给定一个整数,将其转换为罗马数字。输入保证在从1到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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: