Back to challenges
Easy 0 solved 0% acceptance

Roman Numeral Value

Convert a Roman numeral to a number.

What you'll learn

  • Map symbols to values with a dictionary
  • Handle subtractive pairs like IV and XC
  • Scan a string while looking at the next character

Problem

Convert a valid Roman numeral to its value. Symbols are I=1, V=5, X=10, L=50, C=100, D=500, M=1000; a smaller symbol before a larger one is subtracted (IV = 4, CM = 900).

Implement roman_to_int(text).

Input

text: A valid Roman numeral.

Output

Return its value.

Constraints

1 ≤ value ≤ 3,999

Examples

Example 1
Input:
text = "XIV"

Expected output:
expected = 14
Input:
std::string text = "XIV";

Expected output:
long long expected = 14;
Input:
string text = "XIV";

Expected output:
long expected = 14;

Explanation

X = 10, IV = 4: 14.

Example 2
Input:
text = "MCMXCIV"

Expected output:
expected = 1994
Input:
std::string text = "MCMXCIV";

Expected output:
long long expected = 1994;
Input:
string text = "MCMXCIV";

Expected output:
long expected = 1994;

Explanation

M=1000, CM=900, XC=90, IV=4: 1994.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.

Hint 2

Process the numeral from left to right and compare each symbol with the next one.

Hint 3

Make sure the last symbol is always handled correctly since it has no follower.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.