Given a number in Roman numeral format, convert it to decimal. The values of Roman numerals are as follows: { ‘M’: 1000, ‘D’: 500, ‘C’: 100, ‘L’: 50, ‘X’: 10, ‘V’: 5, ‘I’: 1 } In addition, note that the Roman numeral system uses subtractive notation for numbers such as IV and XL. For the input XIV, for instance, you should return 14.
To convert a Roman numeral to its decimal representation, you can follow the following steps:
- Create a dictionary that maps each Roman numeral character to its corresponding decimal value.
- Initialize a variable called
result
with the value of 0. This variable will hold the decimal representation of the Roman numeral. - Iterate through the Roman numeral characters from left to right.
- For each character, check if the current character represents a smaller value than the next character. If true, it indicates that the current character should be subtracted from the next character to form a valid subtractive notation.
- If subtractive notation is present, subtract the value of the current character from the
result
variable. - If subtractive notation is not present, add the value of the current character to the
result
variable. - Finally, return the
result
variable.
Here’s the Java code that implements this algorithm:
import java.util.HashMap;
import java.util.Map;
public class RomanToDecimal {
public static int romanToDecimal(String romanNumeral) {
Map<Character, Integer> romanToDecimalMap = new HashMap<>();
romanToDecimalMap.put('M', 1000);
romanToDecimalMap.put('D', 500);
romanToDecimalMap.put('C', 100);
romanToDecimalMap.put('L', 50);
romanToDecimalMap.put('X', 10);
romanToDecimalMap.put('V', 5);
romanToDecimalMap.put('I', 1);
int result = 0;
int n = romanNumeral.length();
for (int i = 0; i < n; i++) {
int currentNumeralValue = romanToDecimalMap.get(romanNumeral.charAt(i));
if (i < n - 1 && currentNumeralValue < romanToDecimalMap.get(romanNumeral.charAt(i + 1))) {
result -= currentNumeralValue;
} else {
result += currentNumeralValue;
}
}
return result;
}
public static void main(String[] args) {
String romanNumeral = "XIV";
int result = romanToDecimal(romanNumeral);
System.out.println(result); // Output: 14
}
}
And here’s the JavaScript code:
function romanToDecimal(romanNumeral) {
const romanToDecimalMap = {
M: 1000,
D: 500,
C: 100,
L: 50,
X: 10,
V: 5,
I: 1,
};
let result = 0;
const n = romanNumeral.length;
for (let i = 0; i < n; i++) {
const currentNumeralValue = romanToDecimalMap[romanNumeral.charAt(i)];
if (i < n - 1 && currentNumeralValue < romanToDecimalMap[romanNumeral.charAt(i + 1)]) {
result -= currentNumeralValue;
} else {
result += currentNumeralValue;
}
}
return result;
}
const romanNumeral = "XIV";
const result = romanToDecimal(romanNumeral);
console.log(result); // Output: 14