問題
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 つずつ開いてみましょう。
ヒント 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用に調整されています。上記の説明と制約に従ってください。