Amazon interview question

Roman to Int

Interview Answers

Anonymous

19 Oct 2012

Your answer is incorrect. This is how you should have done it: public static int romanToLatin(String romanNumber) throws Exception { HashMap romanLetters = new HashMap(); romanLetters.put("I", 1); romanLetters.put("V", 5); romanLetters.put("X", 10); romanLetters.put("L", 50); romanLetters.put("C", 100); romanLetters.put("D", 500); romanLetters.put("M", 1000); int stringLength = romanNumber.length() - 1; int result = 0; int last = 0; int sign = 1; int current; for (int i = stringLength; i >= 0; i--) { current = romanLetters.get(romanNumber.subSequence(i, i+1)); if (current > last) { result += current; sign = 1; } else if (current == last) { result += current * sign; } else { result -= current; sign = -1; } last = current; } return result; }

1

Anonymous

29 Jul 2012

create a dictionary of std. roman values, parse through the roman string and match with the dictionary values -- keep incrementing the output as you iterate and keep truncating the input string as you go through