Problema
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.
Vincoli
1 ≤ value ≤ 3,999
Esempi
Input:
text = "XIV"
Output atteso:
expected = 14
Input:
std::string text = "XIV";
Output atteso:
long long expected = 14;
Input:
string text = "XIV";
Output atteso:
long expected = 14;
Spiegazione
X = 10, IV = 4: 14.
Input:
text = "MCMXCIV"
Output atteso:
expected = 1994
Input:
std::string text = "MCMXCIV";
Output atteso:
long long expected = 1994;
Input:
string text = "MCMXCIV";
Output atteso:
long expected = 1994;
Spiegazione
M=1000, CM=900, XC=90, IV=4: 1994.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.
Suggerimento 2
Process the numeral from left to right and compare each symbol with the next one.
Suggerimento 3
Make sure the last symbol is always handled correctly since it has no follower.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.