Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
class Solution {
public:
int romanToInt(string s) {
int len=s.size();
int sum=0,i=0;
while(i<len){
switch(s[i]){
case 'M': sum+=1000;break;
case 'D': sum+=500;break;
case 'C': if(s[i+1]=='M'||s[i+1]=='D'){
sum-=100;
}else{
sum+=100;
}
break;
case 'L': sum+=50; break;
case 'X': if(s[i+1]=='L'||s[i+1]=='C'){
sum-=10;
}else{
sum+=10;
}
break;
case 'V': sum+=5;break;
case 'I': if((i+1)!=len &&(s[i+1]=='V'||s[i+1]=='X')){
sum-=1;
}else{
sum+=1;
}
}
i++;
}
return sum;
}
};