Retour aux défis
Facile 0 résolus 0 % de réussite

Roman Numeral Value

Convert a Roman numeral to a number.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

1 ≤ value ≤ 3,999

Exemples

Exemple 1
Entrée :
text = "XIV"

Sortie attendue :
expected = 14
Entrée :
std::string text = "XIV";

Sortie attendue :
long long expected = 14;
Entrée :
string text = "XIV";

Sortie attendue :
long expected = 14;

Explication

X = 10, IV = 4: 14.

Exemple 2
Entrée :
text = "MCMXCIV"

Sortie attendue :
expected = 1994
Entrée :
std::string text = "MCMXCIV";

Sortie attendue :
long long expected = 1994;
Entrée :
string text = "MCMXCIV";

Sortie attendue :
long expected = 1994;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.