419 · Roman to Integer - LintCode

# Description

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

What is Roman Numeral?

  • https://en.wikipedia.org/wiki/Roman_numerals
  • https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
  • http://baike.baidu.com/view/42061.htm

# Example

Example 1:

Input: "IV"
Output: 4

Example 2:

Input: "XCIX"
Output: 99

# Code

右邊的值 < 左邊的值時, 右邊的值 就變成 負數。

public class Solution {
    /**
     * @param s: Roman representation
     * @return: an integer
     */
    public int romanToInt(String s) {
        int res = 0;
        for (int i = 1; i < s.length(); i++) {
            int prev = getValueOf(s.charAt(i - 1));
            int curr = getValueOf(s.charAt(i));
            
            if (curr <= prev) {                
                res += prev;             
            } else {
                res -= prev;              
            }        
        }
        // 最後一個加上,最右邊的肯定是正數
        res += getValueOf(s.charAt(s.length() - 1));
        return res;
    }
    private int getValueOf(char c) {
        switch(c) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
        }
        return 0;
    }
    /*
    Symbol       Value
    I             1
    V             5
    X             10
    L             50
    C             100
    D             500
    M             1000
    */
}