Implement the romanNumeralToInteger method that converts a Roman numeral string into an integer.

The input contains a Roman numeral string roman. Your task is to convert it into its integer value.

Roman symbols usually add their values, but when a smaller value appears before a larger value, it must be subtracted. For example, IV is 4 and CM is 900.

Example 1

Input
roman (string) = MCMXCIV
Returns (int) 1994

Example 2

Input
roman (string) = III
Returns (int) 3

Example 3

Input
roman (string) = LVIII
Returns (int) 58

Create a map of Roman symbols and their numeric values.

Scan the string from left to right. If the current symbol is smaller than the next symbol, subtract its value because it is part of a subtractive pair. Otherwise, add its value.

This handles normal additions like VIII and subtractive cases like IX, XL, and CM.

Pseudocode:

function romanNumeralToInteger(roman):
    values = map of I=1, V=5, X=10, L=50, C=100, D=500, M=1000
    total = 0
    for i from 0 to length(roman) - 1:
        current = values[roman[i]]
        next = 0
        if i + 1 < length(roman):
            next = values[roman[i + 1]]
        if current < next:
            total = total - current
        else:
            total = total + current
    return total
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.