Roman to Integer in TypeScript

function romanToInt(s: string): number {
    // Map to store the values of Roman numerals
    const romanMap: { [key: string]: number } = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    };

    let result = 0; // Initialize result

    // Iterate through the string
    for (let i = 0; i < s.length; i++) {
        const currentVal = romanMap[s[i]];
        const nextVal = i + 1 < s.length ? romanMap[s[i + 1]] : 0;

        // Compare current value with next value
        if (currentVal < nextVal) {
            // Apply subtraction rule
            result -= currentVal;
        } else {
            // Apply concatenation rule
            result += currentVal;
        }
    }

    return result;
}

// Example usage
console.log(romanToInt("III"));     // Output: 3
console.log(romanToInt("LVIII"));   // Output: 58
console.log(romanToInt("MCMXCIV")); // Output: 1994

PrevNext