Amazon Interview Question: Roman to Int... | Glassdoor

Interview Question

Software Design Engineer In Test Interview Seattle, WA

Roman to Int

Answer

Interview Answer

2 Answers

0

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

Interview Candidate on Jul 28, 2012
1

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;
    }

Ozan Eren Bilgen on Oct 19, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.