Einfach 0 gelöst 0% Erfolgsquote

Roman Numeral Value

Convert a Roman numeral to a number.

Das lernst du

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

Problem

Übersetzung anzeigen

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.

Einschränkungen

1 ≤ value ≤ 3,999

Beispiele

Beispiel 1
Eingabe:
text = "XIV"

Erwartete Ausgabe:
expected = 14
Eingabe:
std::string text = "XIV";

Erwartete Ausgabe:
long long expected = 14;
Eingabe:
string text = "XIV";

Erwartete Ausgabe:
long expected = 14;

Erläuterung

X = 10, IV = 4: 14.

Beispiel 2
Eingabe:
text = "MCMXCIV"

Erwartete Ausgabe:
expected = 1994
Eingabe:
std::string text = "MCMXCIV";

Erwartete Ausgabe:
long long expected = 1994;
Eingabe:
string text = "MCMXCIV";

Erwartete Ausgabe:
long expected = 1994;

Erläuterung

M=1000, CM=900, XC=90, IV=4: 1994.

So gehst du vor

Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.

Hinweis 1

Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.

Hinweis 2

Process the numeral from left to right and compare each symbol with the next one.

Hinweis 3

Make sure the last symbol is always handled correctly since it has no follower.

Erwartete Komplexität

O(n) time, O(1) extra space

Referenzen

Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.