Tutorialspoint
Problem
Solution
Submissions

Roman to Integer Conversion

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a Java program to convert a Roman numeral to an integer. Roman numerals are represented by combinations of letters from the Latin alphabet: I, V, X, L, C, D, and M.

Example 1
  • Input: s = "III"
  • Output: 3
  • Explanation:
    • Step 1: "III" consists of three I's.
    • Step 2: I represents 1 in Roman numeral.
    • Step 3: 1 + 1 + 1 = 3.
Example 2
  • Input: s = "MCMXCIV"
  • Output: 1994
  • Explanation:
    • Step 1: "MCMXCIV" consists of the following Roman numerals.
    • Step 2: M = 1000, CM = 900, XC = 90, IV = 4.
    • Step 3: 1000 + 900 + 90 + 4 = 1994.
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)
NumberGoogleSnowflake
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 numerals to their corresponding integer values
  • Traverse the string from left to right
  • If the current value is greater than or equal to the next value, add it to the result
  • If the current value is less than the next value, subtract it from the result
  • Return the final result

Steps to solve by this approach:

 Step 1: Create a HashMap to store the mapping of Roman numerals to their corresponding integer values.
 Step 2: Initialize a result variable to 0.
 Step 3: Iterate through the input string from left to right.
 Step 4: For each character, check if it's the last character or its value is greater than or equal to the next character.
 Step 5: If true, add the current character's value to the result; otherwise, subtract it.
 Step 6: Continue until all characters are processed.
 Step 7: Return the final result.

Submitted Code :