13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution

(1) Java

public int romanToInt(String s) {
        Map<Character, Integer> roms = new HashMap<>();
        roms.put('M', 1000);
        roms.put('D', 500);
        roms.put('C', 100);
        roms.put('L', 50);
        roms.put('X', 10);
        roms.put('V', 5);
        roms.put('I', 1);
        char[] chars = s.toCharArray();
        int rst = 0;
        for (int i = chars.length-1; i >= 0; i--) {
            if (i != chars.length-1 && roms.get(chars[i]) < roms.get(chars[i+1])) {
                rst -= roms.get(chars[i]);
            } else {
                rst += roms.get(chars[i]);
            }
        }
        return rst;
    }

(2) Python

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roms = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
        rst = 0
        for i in range(len(s)-1, -1, -1):
            if i != len(s)-1 and roms[s[i]]<roms[s[i+1]]:
                rst -= roms[s[i]]
            else:
                rst += roms[s[i]]
        return rst

(3) Scala

If you want to use the tuple (a, (k, v))syntax, you need to tell the compiler to use pattern matching with curly braces:

object Solution {
    def romanToInt(s: String): Int = {
        val roms = Map('M'->1000, 'D'->500, 'C'->100, 'L'->50, 'X'->10, 'V'->5, 'I'->1)
        s.map(roms).foldLeft((0,0)){case ((sum,prev), curr)=>if (prev<curr) (sum-2*prev+curr,curr) else (sum+curr,curr)}._1
    }
}

results matching ""

    No results matching ""