簡単 1件解決済み 正答率100.0%

Roman Numeral Value

Convert a Roman numeral to a number.

このチャレンジで学べること

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

問題

翻訳を表示

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

例

例 1
入力:
text = "XIV"

期待される出力:
expected = 14
入力:
std::string text = "XIV";

期待される出力:
long long expected = 14;
入力:
string text = "XIV";

期待される出力:
long expected = 14;

解説

X = 10, IV = 4: 14.

例 2
入力:
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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 HJhettory Jurash Python 807 ms - 3/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意:下に1件の全解答あり まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。