Open In App
Related Articles

Convert a Roman Number to Decimal using Hashmap in Java

Improve Article
Save Article
Like Article

Given a Roman numeral, the task is to find the corresponding decimal value.

Note: Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.


Input: “III”

Output: 3

Input: “MDCCLX”

Output: 1760


  1. Loop through each character in the string containing the Roman numerals.
  2. Compare the value of the current roman symbol with the value of the roman symbol to its right. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total.

Below is the implementation of the above approach:


// Java Program to Convert a Roman
// Number to Decimal using Hashmap
import java.util.Scanner;
import java.util.HashMap;
class solution {
    int romanToInt(String s)
        // Create a empty hash map.
        HashMap<Character, Integer> map = new HashMap<>();
        // Putting value in hash map.
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        // Creating integer variable to store result.
        int result = 0;
        // initialize loop to iterate in string.
        for (int i = 0; i < s.length(); i++) {
            // Checking that current element
            // is not smaller then previous
            if (i > 0
                && map.get(s.charAt(i))
                       > map.get(s.charAt(i - 1))) {
                result += map.get(s.charAt(i))
                          - 2 * map.get(s.charAt(i - 1));
            else {
                result += map.get(s.charAt(i));
        // Returning the integer value of Roman number.
        return result;
public class GFG {
    public static void main(String[] args)
        String s;
        // Scanner sc = new Scanner(;
        // s = sc.nextLine();
        solution gfg = new solution();



Time Complexity: O(N)

Auxiliary Space: O(1)

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated : 30 Mar, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials