Easy Problems

13. Roman to Integer

What will be learned

  • Practice parsing strings and understand the importance of hash tables in mapping characters to values.

Solutions

const map = {
  'I': 1,
  'V': 5,
  'X': 10,
  'L': 50,
  'C': 100,
  'D': 500,
  'M': 1000,
}
 
function romanToInt(s: string): number {
  let result = 0;
  for(let i = 0; i < s.length; i++) {
      if(map[s[i]] < map[s[i + 1]]) {
          result = result - map[s[i]] + map[s[i + 1]]
          i++;
      } else {
          result += map[s[i]]
      }
  }
  return result;
};

Video Solution

...I think it's a really good problem to, you know, to practice your problem solving skill.

Last Update: 12:08 - 16 April 2024
Hash Table
Math
String

On this page