Monday, September 14, 2015

Roman to Integer | Leetcode

Given a roman numeral, convert it to an integer.
 
Input is guaranteed to be within the range from 1 to 3999.

---

Solution: The integer value can be derived by greedily going through the string from left to right and then recognizing its current immediate substring on the left.
public class Solution {
    private String s;
    private int i = 0;
    private int n = 0;
    
    public int romanToInt(String s) {
        this.s = s;
        fromRoman("M", 1000);
        fromRoman("CM", 900);
        fromRoman("D", 500);
        fromRoman("CD", 400);
        fromRoman("C", 100);
        fromRoman("XC", 90);
        fromRoman("L", 50);
        fromRoman("XL", 40);
        fromRoman("X", 10);
        fromRoman("IX", 9);
        fromRoman("V", 5);
        fromRoman("IV", 4);
        fromRoman("I", 1);
        return n;
    }
    
    private int fromRoman(String roman, int value) {
        while (s.indexOf(roman, i) == i) {
            n += value;
            i += roman.length();
        }
        return n;
    }
}

No comments: