请将给出的罗马数字转化为整数
保证输入的数字范围在1 到 3999之间。
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这道题会有点乱,不够简化
public static int romanToInt (String s) { int ans=0; boolean sign = false; char[] array = s.toCharArray();//把他拆成数组 int[] sn = new int[]{1,4,5,9,10,40,50,90,100,400,500,900,1000}; String[] st=new String[]{"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};//两个比对的数组 for(int i =0;i<array.length;i++){ sign = false; StringBuffer sb = new StringBuffer(); if(i<array.length-1){ sb.append(array[i]); sb.append(array[i+1]); for(int j =st.length-1;j>=0;j--){ if(st[j].equals(sb.toString())){ ans+=sn[j]; sign=true; i++;break; } } }//先判断是否构成两个数字的罗马文字 if(!sign){ for(int j =st.length-1;j>=0;j--){ String value = new String(""+array[i]); if(st[j].equals(value)){ ans+=sn[j]; //单个文字就直接给加上ans break; } } } System.out.println(ans); } return ans; }