您的位置:首页 > 其它

[LeetCode] 13.Roman to Integer

2017-09-11 00:11 316 查看

[LeetCode] 13.Roman to Integer

罗马数字与阿拉伯数字的关系

罗马数字的组数规则

题目描述

解题思路

实验代码

罗马数字与阿拉伯数字的关系

基本字符相应的阿拉伯数字
I1
V5
X10
L50
C100
D500
M1000

罗马数字的组数规则

1.基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;

2.不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个。

题目描述

Given a roman numeral, convert it to an integer.

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

解题思路

与第12题类似,道理是相同的,只不过是反着来而已。所以解题思路在了解了罗马数字的特点以及其和阿拉伯数字的关系之后也很快能出来。

这次我选择使用了map容器解决问题,因为感觉用字符表示相应的阿拉伯数字更加方便也更加有效。

实验代码

class Solution {
public:
int romanToInt(string s) {
int l = s.length();
if (l == 0) return 0;
map<char, int> m;
m['M'] = 1000;
m['D'] = 500;
m['C'] = 100;
m['L'] = 50;
m['X'] = 10;
m['V'] = 5;
m['I'] = 1;
int integer = m[s[l-1]];
for (int i = l-2; i >= 0; i--) {
if (m[s[i+1]] <= m[s[i]])
integer += m[s[i]];
else integer -= m[s[i]];
}
return integer;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: