原题链接:https://leetcode.com/problemset/algorithms/
原题:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题意:给你一个罗马数字的字符串,要求你翻译成整数。
思路:
首先需要知道罗马数字的翻译规则:
基本字符:
I、V、X、L、C、D、M
相应的阿拉伯数字表示为:
1.5、10、50、100、500、1000
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如:Ⅷ = 8;Ⅻ = 12;
(3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
所以,我们用一个hash来储存罗马基本字符对应的数字,然后按基本规则翻译即可。注意,字符串要从后面开始遍历。
AC代码:
class Solution {
public:
int romanToInt(string s) {
int map[56];
map['I'-'A']=1;
map['V'-'A']=5;
map['X'-'A']=10;
map['L'-'A']=50;
map['C'-'A']=100;
map['D'-'A']=500;
map['M'-'A']=1000;
int result=0;
int max=0;
for(int i=s.length()-1;i>=0;i--){
if(map[s[i]-'A']>=max){
result+=map[s[i]-'A'];
max=map[s[i]-'A'];
}
else {
result-=map[s[i]-'A'];
}
}
return result;
}
};