Convert a Roman Number to Decimal using Hashmap in Java
Last Updated :
29 Feb, 2024
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:
- Loop through each character in the string containing the Roman numerals.
- 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
import java.io.*;
import java.util.Scanner;
import java.util.HashMap;
class solution {
int romanToInt(String s)
{
HashMap<Character, Integer> map = new HashMap<>();
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 );
int result = 0 ;
for ( int i = 0 ; i < s.length(); i++) {
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));
}
}
return result;
}
}
public class GFG {
public static void main(String[] args)
{
String s;
solution gfg = new solution();
System.out.println(gfg.romanToInt( "MDCCLX" ));
}
}
|
Output:
1760
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...