描述
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
分析
从前往后扫描,用一个临时变量记录分段数字。
如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如 IV = 5 – 1;否
则,将当前值加入到结果中,然后开始下一段记录。比如 VI = 5 + 1, II=1+1
代码
1 public class RomanToInteger { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 String roman = "CLXXXVII"; 6 System.out.println(romanToInteger2(roman)); 7 } 8 9 public static int romanToInteger(String roman) { 10 // int num=0; 11 // int radix[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 12 // String symbol[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", 13 // "V", "IV", "I" }; 14 if (roman.length() > 0) { 15 if (roman.charAt(0) == 'M') { 16 roman = roman.substring(1); 17 return 1000 + romanToInteger(roman); 18 } 19 if (roman.contains("CM")) { 20 roman = roman.substring(2); 21 return 900 + romanToInteger(roman); 22 } 23 if (roman.charAt(0) == 'D') { 24 roman = roman.substring(1); 25 return 500 + romanToInteger(roman); 26 } 27 if (roman.contains("CD")) { 28 roman = roman.substring(2); 29 return 400 + romanToInteger(roman); 30 } 31 if (roman.charAt(0) == 'C') { 32 roman = roman.substring(1); 33 return 100 + romanToInteger(roman); 34 } 35 if (roman.contains("XC")) { 36 roman = roman.substring(2); 37 return 90 + romanToInteger(roman); 38 } 39 if (roman.charAt(0) == 'L') { 40 roman = roman.substring(1); 41 return 50 + romanToInteger(roman); 42 } 43 if (roman.contains("XL")) { 44 roman = roman.substring(2); 45 return 40 + romanToInteger(roman); 46 } 47 if (roman.charAt(0) == 'X') { 48 roman = roman.substring(1); 49 return 10 + romanToInteger(roman); 50 } 51 if (roman.contains("IX")) { 52 roman = roman.substring(2); 53 return 9 + romanToInteger(roman); 54 } 55 if (roman.charAt(0) == 'V') { 56 roman = roman.substring(1); 57 return 5 + romanToInteger(roman); 58 } 59 if (roman.contains("IV")) { 60 roman = roman.substring(2); 61 return 4 + romanToInteger(roman); 62 } 63 if (roman.charAt(0) == 'I') { 64 roman = roman.substring(1); 65 return 1 + romanToInteger(roman); 66 } 67 } 68 return 0; 69 }
以下是不用递归的方法(转载)
1 private static int map(char c) { 2 switch (c) { 3 case 'I': 4 return 1; 5 case 'V': 6 return 5; 7 case 'X': 8 return 10; 9 case 'L': 10 return 50; 11 case 'C': 12 return 100; 13 case 'D': 14 return 500; 15 case 'M': 16 return 1000; 17 default: 18 return 0; 19 } 20 } 21 22 public static int romanToInteger2(String s) { 23 int result = 0; 24 char[] sch = s.toCharArray(); 25 for (int i = 0; i < sch.length; i++) { 26 if (i > 0 && map(sch[i]) > map(sch[i - 1])) { 27 result += (map(sch[i]) - 2 * map(sch[i - 1])); 28 } else { 29 result += map(sch[i]); 30 } 31 } 32 return result; 33 }