这道题目不难,就是麻烦,分析好条件一步一步去匹配就好。
class Solution {
public:
int romanToInt(string s) {
int strLength = s.size();
int res = 0;
for(int i=0;i<s.size();i++){
if(s[i] == 'I'){
if(i+1<s.size()&&s[i+1] == 'V'){
res += 4;
i++;
continue;
}else if(i+1<s.size()&&s[i+1] == 'X'){
res += 9;
i++;
continue;
}
else{
res+=1;
continue;
}
}else if(s[i] == 'V'){
res +=5;
}else if(s[i] == 'X'){
if(i+1<s.size()&&s[i+1] == 'L'){
res +=40;
i++;
continue;
}else if(i+1<s.size()&&s[i+1] == 'C'){
res +=90;
i++;
continue;
}else {
res +=10;
continue;
}
}else if(s[i] == 'L'){
res += 50;
}else if(s[i] == 'C'){
if(i+1<s.size()&&s[i+1] == 'D'){
res +=400;
i++;
continue;
}else if(i+1<s.size()&&s[i+1] == 'M'){
res +=900;
i++;
continue;
}else {
res += 100;
continue;
}
}else if(s[i] == 'D'){
res += 500;
continue;
}else if(s[i] == 'M'){
res += 1000;
continue;
}
}
return res;
}
};