Leetcode: Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
从右向左,preVal, curVal
1. curVal >= preVal: res+=curVal
2. curVal < preVal: res -= curVal
1 public class Solution { 2 public static int romanToInt(String s) { 3 int res = 0; 4 int preVal = 0; 5 for (int i = s.length() - 1; i >= 0; i--) { 6 char c = s.charAt(i); 7 int curVal = 0; 8 switch (c) { 9 case 'I': 10 curVal = 1; 11 break; 12 case 'V': 13 curVal = 5; 14 break; 15 case 'X': 16 curVal = 10; 17 break; 18 case 'L': 19 curVal = 50; 20 break; 21 case 'C': 22 curVal = 100; 23 break; 24 case 'D': 25 curVal = 500; 26 break; 27 case 'M': 28 curVal = 1000; 29 break; 30 } 31 if (curVal >= preVal) res += curVal; 32 else res -= curVal; 33 preVal = curVal; 34 } 35 return res; 36 } 37 }