Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:
1.首先了解罗马数字:
I:1
V:5
X:10
L:50
C:100
D:500
M:1000
V和X左边的小数字只能用Ⅰ。
L和C左边的小数字只能用X。
D和M左边的小数字只能用C。
即:IV=4,IX=9,XL=40,XC=90,CD=400,CM=900
2.重点就是判断IV,IX,XL,XC,CD,CM 六个数。利用循环遍历字符串,然后分别判断各种情况,特别注意考虑到边界情况。这道题我好多种情况没有考虑到,后来在调试的修改了3次才AC。代码写的太长,不太好,以后改进。
代码:
public class Solution {
public int romanToInt(String s) {
int result=0;
int ci=0,cv=0,cx=0,cl=0,cc=0,cd=0,cm=0;
int civ=0,cix=0,cxl=0,cxc=0,ccd=0,ccm=0;
if(s.isEmpty()) return 0;
else if(s.charAt(0)=='M'||s.charAt(0)=='m') cm++;
else if(s.charAt(0)=='D'||s.charAt(0)=='d') cd++;
else if(s.charAt(0)=='C'||s.charAt(0)=='c') {
if(s.length()==1) cc++;
else if(s.charAt(1)!='D'&&s.charAt(1)!='d'&&s.charAt(1)!='M'&&s.charAt(1)!='m')
cc++;
}
else if(s.charAt(0)=='L'||s.charAt(0)=='l') cl++;
else if(s.charAt(0)=='X'||s.charAt(0)=='x') {
if(s.length()==1) cx++;
else if(s.charAt(1)=='L'||s.charAt(1)=='l'||s.charAt(1)=='C'||s.charAt(1)=='c') ;
else cx++;
}
else if(s.charAt(0)=='V'||s.charAt(0)=='v') cv++;
else if(s.charAt(0)=='I'||s.charAt(0)=='i'){
if(s.length()==1) ci++;
else if(s.charAt(1)=='I'||s.charAt(1)=='i') ci++;
}
for(int i=1;i<s.length();i++){
if(s.charAt(i)=='M'||s.charAt(i)=='m'){
if(s.charAt(i-1)=='C'||s.charAt(i-1)=='c') ccm++;
else cm++;
}
else if(s.charAt(i)=='D'||s.charAt(i)=='d'){
if(s.charAt(i-1)=='C'||s.charAt(i-1)=='c') ccd++;
else cd++;
}
else if(s.charAt(i)=='C'||s.charAt(i)=='c'){
if(s.charAt(i-1)=='X'||s.charAt(i-1)=='x') cxc++;
else if(i==s.length()-1) ++cc;
else if(s.charAt(i+1)=='D'||s.charAt(i+1)=='d'||s.charAt(i+1)=='M'||s.charAt(i+1)=='m') continue;
else cc++;
}
else if(s.charAt(i)=='L'||s.charAt(i)=='l'){
if(s.charAt(i-1)=='X'||s.charAt(i-1)=='x') cxl++;
else cl++;
}
else if(s.charAt(i)=='X'||s.charAt(i)=='x'){
if(s.charAt(i-1)=='I'||s.charAt(i-1)=='i') cix++;
else if(i==s.length()-1) cx++;
else if(s.charAt(i+1)=='L'||s.charAt(i+1)=='l'||s.charAt(i+1)=='C'||s.charAt(i+1)=='c') continue;
else cx++;
}
else if(s.charAt(i)=='V'||s.charAt(i)=='v'){
if(s.charAt(i-1)=='I'||s.charAt(i-1)=='i') civ++;
else cv++;
}
else if(s.charAt(i)=='I'||s.charAt(i)=='i'){
if(i==s.length()-1) ci++;
else if(s.charAt(i+1)=='I'||s.charAt(i+1)=='i') ci++;
else continue;
}
}
result=ci*1+cv*5+cx*10+cl*50+cc*100+cd*500+cm*1000
+civ*4+cix*9+cxl*40+cxc*90+ccd*400+ccm*900;
return result;
}
}