-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
41 lines (33 loc) · 829 Bytes
/
RomanToInteger.java
File metadata and controls
41 lines (33 loc) · 829 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
38
39
40
41
package math;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/roman-to-integer
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class RomanToInteger {
public int romanToInt(String s) {
Map<Character, Integer> map = Map.of(
'I', 1,
'V', 5,
'X', 10,
'L', 50,
'C', 100,
'D', 500,
'M', 1000);
int result = 0;
int prev = 0;
for (char c : s.toCharArray()) {
int current = map.get(c);
if (current > prev) {
result -= prev;
} else {
result += prev;
}
prev = current;
}
result += prev;
return result;
}
}