Условие
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.
Ограничения
1 ≤ value ≤ 3,999
Примеры
Ввод:
text = "XIV"
Ожидаемый вывод:
expected = 14
Ввод:
std::string text = "XIV";
Ожидаемый вывод:
long long expected = 14;
Ввод:
string text = "XIV";
Ожидаемый вывод:
long expected = 14;
Пояснение
X = 10, IV = 4: 14.
Ввод:
text = "MCMXCIV"
Ожидаемый вывод:
expected = 1994
Ввод:
std::string text = "MCMXCIV";
Ожидаемый вывод:
long long expected = 1994;
Ввод:
string text = "MCMXCIV";
Ожидаемый вывод:
long expected = 1994;
Пояснение
M=1000, CM=900, XC=90, IV=4: 1994.
Как подступиться
Сначала попробуйте сами, затем открывайте подсказки по одной.
Подсказка 1
Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.
Подсказка 2
Process the numeral from left to right and compare each symbol with the next one.
Подсказка 3
Make sure the last symbol is always handled correctly since it has no follower.
Ожидаемая сложность
O(n) time, O(1) extra space
Ссылки
Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.