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
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.
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.