Question: a string of Roman numerals must be converted to a decimal number.
Algorithm:
Calculate from right to left:
1. If the right side is <= left side, add
2. If the right side is greater than the left side, subtraction is performed.
/** * Calculate from right to left. following the rules below: * 1. if right <= left, then result := right+left * 2. or result := abs(result-left) * * @author ouyangyewei */public class Solution { public int romanToInt(String s) { final String ROMAN_STRING = "IVXLCDM"; final int[] ROMAN_VALUE = new int[]{1,5,10,50,100,500,1000}; char lastRoman = 'I'; char currRoman = '\0'; int result = 0; int length = s.length(); for (int i=length-1; i>=0; --i) { currRoman = s.charAt(i); int lastRomanValue = ROMAN_VALUE[ROMAN_STRING.lastIndexOf(lastRoman)]; int currRomanValue = ROMAN_VALUE[ROMAN_STRING.lastIndexOf(currRoman)]; if (lastRomanValue <= currRomanValue) { result += currRomanValue; } else { if (result > currRomanValue) { result = result - currRomanValue; } else { result = currRomanValue - result; } } lastRoman = currRoman; } return result; }}