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;
}
};
题目:
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;
}
};
相关文章推荐
- [leedcode oj 13]Roman to Integer
- LEEDCODE 13 Roman to Integer (JAVA题解)
- LEEDCODE 12 Integer to Roman (JAVA题解)
- LeedCode String to Integer (atoi)
- leatcode 13,Roman to Integer
- [leedcode oj 8]String to Integer (atoi)
- LeedCode OJ -- String to Integer (atoi)
- [leet code] Integer to Roman
- [LeedCode OJ]#8 String to Integer (atoi)
- CODE 118: Roman to Integer
- (LEEDCODE)String to Integer (atoi) 字符串转整型
- CODE 119: Integer to Roman
- Leet Code 13 Roman to Integer - 罗马数字转成整数 - Java
- Lettcode_13_Roman to Integer——罗马数字转变算法
- Leet Code 12 Integer to Roman - 整数转成罗马数字 - Java
- [leet code] Roman to Integer
- Lettcode_12_Integer to Roman
- lintcode :Integer to Roman 整数转罗马数字
- leetcode Roman to Integer 2.5 难度系数2
- Roman to Integer-LeetCode JavaScript