13. Roman numerals to integers (LeetCode) (leetcode-cn.com)

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

I             1
V             5
X             10
L             50
C             100
D             500
M             1000
Copy the code

For example, the Roman numeral 2 is written II, which means two 1s side by side. Let’s write 12 as XII, which is X plus II. 27 write XXVII, XX + V + II.

In Roman numerals, the smaller number is usually placed to the right of the larger number. But there are exceptions. For example, instead of writing IIII for 4, I would write IV. The number 1 is to the left of the number 5, which is equal to the large number 5 and the number 4 is obtained by reducing the number 1. Similarly, the number 9 is represented as IX. This particular rule only applies in the following six cases:

I can be placed to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be placed to the left of D (500) and M (1000) to represent 400 and 900. Given a Roman numeral, convert it to an integer. Make sure the input is in the range 1 to 3999.

Example 1:

Input: "III" Output: 3Copy the code

Example 2:

Input: "IV" Output: 4Copy the code

Example 3:

Input: "IX" Output: 9Copy the code

Example 4:

Input: "LVIII" Output: 58 Description: L = 50, V= 5, III = 3.Copy the code

Example 5:

Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90, IV = 4.Copy the code

If the current digit is greater than or equal to the last digit, add it, otherwise subtract it

By code:

 * @param {string} s
 * @return {number}
 */
var romanToInt = function (s) {
    let m = new Map()
    m.set('I', 1)
    m.set('V', 5)
    m.set('X', 10)
    m.set('L', 50)
    m.set('C', 100)
    m.set('D', 500)
    m.set('M', 1000)

    let sum = 0

    for (let i = 0; i < s.length; i++) {
        const a = m.get(s[i])
        const b = m.get(s[i + 1]) || 0
        a >= b ? sum += a : sum-= a
    }

    return sum
};
Copy the code