-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram137.java
More file actions
39 lines (31 loc) · 1.01 KB
/
Program137.java
File metadata and controls
39 lines (31 loc) · 1.01 KB
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
import java.util.HashMap;
class RomanToInteger {
public static void main(String[] args) {
String roman = "MCMXCIV";
int result = romanToInteger(roman);
System.out.println("Roman numeral: " + roman);
System.out.println("Integer equivalent: " + result);
}
public static int romanToInteger(String s) {
HashMap<Character, Integer> romanValues = new HashMap();
romanValues.put('I', 1);
romanValues.put('V', 5);
romanValues.put('X', 10);
romanValues.put('L', 50);
romanValues.put('C', 100);
romanValues.put('D', 500);
romanValues.put('M', 1000);
int result = 0;
int prevValue = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int value = romanValues.get(s.charAt(i));
if (value < prevValue) {
result -= value;
} else {
result += value;
}
prevValue = value;
}
return result;
}
}