一.题目描述
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) {
map<string,int> hash_map;
const int int_sub[]={4,9,40,90,400,900,1,5,10,50,100,500,1000};
const string sub[] ={"IV","IX","XL","XC","CD","CM","I","V","X","L","C","D","M"};
for(int i=0;i<sizeof(int_sub)/sizeof(int);i++)
hash_map[sub[i]]=int_sub[i];
int i=0;
string tmp("");
int res=0;
char curr='0';char next='0';
while( i<s.length())
{
tmp=s[i];
if(i<s.length()-1)
{
tmp=tmp+s[i+1];
if(hash_map[tmp]>0)
{
res=res+hash_map[tmp];
i=i+2;
continue;
}
}
tmp=s[i];
res=res+hash_map[tmp];
i++;
}
return res;
}
};

本文介绍了一种将罗马数字转换为整数的算法实现,包括解析罗马数字字符串并计算其对应整数值的过程。
2115

被折叠的 条评论
为什么被折叠?



