-
Notifications
You must be signed in to change notification settings - Fork 0
/
RomanToIntegerConverter.java
44 lines (35 loc) · 1.28 KB
/
RomanToIntegerConverter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package arrayslogical;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class RomanToIntegerConverter {
public static int romanToInteger(String roman) {
Map<Character, Integer> romanToIntegerMap = new HashMap<>();
romanToIntegerMap.put('I', 1);
romanToIntegerMap.put('V', 5);
romanToIntegerMap.put('X', 10);
romanToIntegerMap.put('L', 50);
romanToIntegerMap.put('C', 100);
romanToIntegerMap.put('D', 500);
romanToIntegerMap.put('M', 1000);
int result = 0;
int prevValue = 0;
for (int i = roman.length() - 1; i >= 0; i--) {
int value = romanToIntegerMap.get(roman.charAt(i));
if (value < prevValue) {
result -= value;
} else {
result += value;
}
prevValue = value;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Roman numeral: ");
String roman = scanner.nextLine().toUpperCase();
int result = romanToInteger(roman);
System.out.println("The integer equivalent of " + roman + " is: " + result);
}
}