题解:从左往右,如果s[i]>=s[i+1]相加,否则相减。
1.Switch
class Solution {
public:
int romanToInt(string s) {
int res=0;
for(int i=0;i<s.length();i++){
if(getValue(s[i])>=getValue(s[i+1])) res+=getValue(s[i]);
else res-=getValue(s[i]);
}
return res;
}
int getValue(char c){
switch(c){
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;}
return 0;
}
};
2.HashMap
建立一个HashMap来映射符号和值,然后对字符串从左到右来,如果当前字符代表的值不小于其右边,就加上该值;否则就减去该值。以此类推到最左边的数,最终得到的结果即是答案。
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int> hashmap={
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};
//遍历
int res=0;
9 for(int i=0;i<s.length();i++){
if(hashmap[s[i]]>=hashmap[s[i+1]]) res+=hashmap[s[i]];
else res-=hashmap[s[i]];
}
return res;
}
};