Open In App

Convert a Roman Number to Decimal using Hashmap in Java

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples:

Input: “III”

Output: 3

Input: “MDCCLX”

Output: 1760

Approach:

  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




// Java Program to Convert a Roman
// Number to Decimal using Hashmap
import java.io.*;
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(System.in);
        // s = sc.nextLine();
        solution gfg = new solution();
        System.out.println(gfg.romanToInt("MDCCLX"));
    }
}


Output:

1760

Time Complexity: O(N)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads