LeetCode Roman to Integer
发布时间:2020-12-13 20:13:09 所属栏目:PHP教程 来源:网络整理
导读:Given a roman numeral,convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 题意:讲罗马数字转换成阿拉伯数字 思路:了解罗马数字的构造后,从后往前处理就好了 class Solution {public: int romanToInt(string s) { i
Given a roman numeral,convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 题意:讲罗马数字转换成阿拉伯数字思路:了解罗马数字的构造后,从后往前处理就好了 class Solution {
public:
int romanToInt(string s) {
if (s.size() == 0) return 0;
map<char,int> mp;
mp['I'] = 1;
mp['V'] = 5;
mp['X'] = 10;
mp['L'] = 50;
mp['C'] = 100;
mp['D'] = 500;
mp['M'] = 1000;
int len = s.size();
int sum = mp[s[len⑴]];
for (int i = len⑵; i >= 0; i--) {
if (mp[s[i]] < mp[s[i+1]])
sum -= mp[s[i]];
else sum += mp[s[i]];
}
return sum;
}
};
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |