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)
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