13. Roman to Integer - Easy

 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written from largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract is making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V(5) and X(10) to make 4 and 9
  • X can be placed before L(50) and C(100) to. make 40 and 90
  • C can be placed before D(500) and M(1000) to make 400 and 900
Given a roman numeral, convert it to an integer.

Example:
Input: s = "III"
Output: 3
Explanation: III = 3

Constraints:
  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
  • It is guaranteed that s is valid roman numeral in the range [1,3999]
Solution:
I thought this might work:

var romanToInt = function(s) {
    const mapping = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    };
    let sum = 0;

    for(let i = 0; i < s.length; i++) {
        if (mapping[s[i]]) {
            sum += mapping[s[i]];
        }
    }
    return sum;
};

However it fails when you come up against a roman numeral like IV which is 4 and not 6. So this solution can pass a few test cases but nowhere near enough for it to be a working solution. 

This solution works for all cases:
var romanToInt = function(s) {
        const mapping = {
         'I': 1,
         'V': 5,
         'X': 10,
         'L': 50,
         'C': 100,
         'D': 500,
         'M': 1000
        };

    let res = 0;

    for (let i = 0; i < s.length; i++) {
        const curr = mapping[s[i]];
        const next = mapping[s[i+1]];

        if (curr < next) {
            res += next - curr;
            i++;
          } else {
            res += curr;
           }
    return res;
}

Thoughts:
I learnt that in roman numerals, it's only ever the one before the major values, e.g. V, X, L etc where it displays as the next value minus the current value if that makes sense so VIII is 8 but IX is 9. It's not VIIII or 8 isn't IIX. So you only ever have to look for the 9th value. It was difficult to solve so I gave up and had a look at the solutions. I would rate my understanding a 5/10. Not having the best of days so far.

Comments

Popular posts from this blog

28. Find the Index of the First Occurence in a String - Easy

121. Best Time to Buy and Sell Stock - Easy

58. Length of Last Word - Easy