Tutorialspoint
Problem
Solution
Submissions

Convert Roman to Integer

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to convert a Roman numeral string to its integer equivalent. Roman numerals are represented by seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Roman numerals are usually written from largest to smallest from left to right. However, in some cases, a smaller numeral appears before a larger one to indicate subtraction (e.g., IV = 4, IX = 9).

Example 1
  • Input: s = "LVIII"
  • Output: 58
  • Explanation:
    • Break down the Roman numeral: L = 50, V = 5, I = 1, I = 1, I = 1.
    • Since all symbols are in descending order, simply add them.
    • 50 + 5 + 1 + 1 + 1 = 58.
    • Therefore, "LVIII" equals 58.
Example 2
  • Input: s = "MCMXC"
  • Output: 1990
  • Explanation:
    • Break down the Roman numeral: M = 1000, C = 100, M = 1000, X = 10, C = 100.
    • CM represents 1000 - 100 = 900 (subtraction case).
    • XC represents 100 - 10 = 90 (subtraction case).
    • M + CM + XC = 1000 + 900 + 90 = 1990.
    • Therefore, "MCMXC" equals 1990.
Constraints
  • 1 ≤ s.length ≤ 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
  • It is guaranteed that s is a valid Roman numeral in the range [1, 3999]
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsNumberTech MahindraAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a mapping of Roman symbols to their integer values
  • Iterate through the string from left to right
  • For each character, check if the next character represents a larger value
  • If the current value is smaller than the next, subtract it (subtraction case)
  • Otherwise, add the current value to the result
  • Handle the last character separately as it has no next character

Steps to solve by this approach:

 Step 1: Create a mapping object that associates each Roman symbol with its integer value.
 Step 2: Initialize a result variable to store the final integer value.
 Step 3: Iterate through each character in the Roman numeral string.
 Step 4: For each character, get its value and the value of the next character (if it exists).
 Step 5: If the current value is less than the next value, subtract it from the result (subtraction case).
 Step 6: Otherwise, add the current value to the result (normal case).
 Step 7: Return the final result after processing all characters.

Submitted Code :