-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
37 lines (32 loc) · 1000 Bytes
/
RomanToInteger.java
File metadata and controls
37 lines (32 loc) · 1000 Bytes
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
import java.util.*;
public class RomanToInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Roman numeral: ");
String roman = sc.nextLine().toUpperCase();
int result = romanToInt(roman);
System.out.println("Integer value: " + result);
}
public static int romanToInt(String s) {
Map<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 sum = 0;
int prev = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int curr = map.get(s.charAt(i));
if (curr < prev) {
sum -= curr;
} else {
sum += curr;
}
prev = curr;
}
return sum;
}
}