June 12th 2023

Roman to Integer — Typescript

Problem Description permalink

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

Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 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 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 it 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.

Solution permalink

function expect(description: string, test: boolean) {
if (test) {
console.log(`${description}`)
} else {
console.log(`${description}`)
}
}

function romanCharToInt(s: string): number {
switch (s) {
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

// Custom subs
case "@":
return 4
case "#":
return 9
case "$":
return 40
case "%":
return 90
case "^":
return 400
case "&":
return 900

default:
return 0
}
}

function romanToInt(s: string): number {
return s
.replace("IV", "@")
.replace("IX", "#")
.replace("XL", "$")
.replace("XC", "%")
.replace("CD", "^")
.replace("CM", "&")
.split("")
.map(romanCharToInt)
.reduce((value, total) => value + total, 0)
};

console.log(romanToInt("IV"))

expect("I is 1", romanToInt("I") == 1)
expect("II is 2", romanToInt("II") == 2)
expect("III is 3", romanToInt("III") == 3)
expect("IV is 4", romanToInt("IV") == 4)
expect("V is 5", romanToInt("V") == 5)
expect("VI is 6", romanToInt("VI") == 6)
expect("IX is 9", romanToInt("IX") == 9)
expect("X is 10", romanToInt("X") == 10)
expect("XL is 40", romanToInt("XL") == 40)
expect("XC is 90", romanToInt("XC") == 90)
expect("LVIII is 58", romanToInt("LVIII") == 58)
expect("MCMXCIV is 1994", romanToInt("MCMXCIV") == 1994)

Discussion permalink

This feels clever but wouldn't scale if there were more and more roman numbers. As the data is pretty constrained this works ok.