-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanToInt.java
More file actions
35 lines (29 loc) · 901 Bytes
/
Copy pathRomanToInt.java
File metadata and controls
35 lines (29 loc) · 901 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
package org.example;
import java.util.HashMap;
public class RomanToInt {
public int romanToInt(String s) {
HashMap<Character, Integer> hashMap = new HashMap<>();
hashMap.put('I', 1);
hashMap.put('V', 5);
hashMap.put('X', 10);
hashMap.put('L', 50);
hashMap.put('C', 100);
hashMap.put('D', 500);
hashMap.put('M', 1000);
int sum = 0;
for (int i = 0; i < s.length(); i++) {
Character curr = s.charAt(i);
if (i + 1 < s.length()) {
Character next = s.charAt(i + 1);
if (hashMap.get(curr) < hashMap.get(next)) {
sum -= hashMap.get(curr);
} else {
sum += hashMap.get(curr);
}
} else {
sum += hashMap.get(curr);
}
}
return sum;
}
}