罗马数字转数字
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
其中,一些特殊规则如下:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
输入一个罗马字符串,转成数字
class Solution {
public int romanToInt(String s) {
int res = 0;
for(int i=0;i<s.length();){
char c = s.charAt(i);
switch(c){
case 'I':
if(i<s.length()-1 && s.charAt(i+1) == 'V'){
res += 4;
i += 2;
}else if(i<s.length()-1 && s.charAt(i+1) == 'X'){
res += 9;
i += 2;
}else{
res += 1;
i+=1;
}
break;
case 'V':
res += 5;
i+=1;
break;
case 'X':
if(i<s.length()-1 && s.charAt(i+1) == 'L'){
res += 40;
i+=2;
}else if(i<s.length()-1 && s.charAt(i+1) == 'C'){
res += 90;
i += 2;
}else{
res += 10;
i+=1;
}
break;
case 'L':
res += 50;
i+=1;
break;
case 'C':
if(i<s.length()-1 && s.charAt(i+1) == 'D'){
res += 400;
i += 2;
}else if(i<s.length()-1 && s.charAt(i+1) == 'M'){
res += 900;
i += 2;
}else{
res += 100;
i+=1;
}
break;
case 'D':
res += 500;
i+=1;
break;
case 'M':
res += 1000;
i+=1;
}
}
return res;
}
}