-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_13_RomanToInteger.java
More file actions
62 lines (44 loc) · 1.41 KB
/
_13_RomanToInteger.java
File metadata and controls
62 lines (44 loc) · 1.41 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.HashMap;
import java.util.Map;
public class _13_RomanToInteger {
static int romanToInteger(String roman){
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 result = 0;
// int prevValue = 0;
// left to right
for (int i = 0; i < roman.length() - 1; i++) {
int curr = map.get(roman.charAt(i));
int next = map.get(roman.charAt(i + 1));
if (curr < next) {
result -= curr;
}else{
result += curr;
}
}
result += map.get(roman.charAt(roman.length() - 1));
// Right To Left
// for (int i = roman.length() - 1; i >= 0; i--) {
// char currItem = roman.charAt(i);
// int currVal = map.get(currItem);
// if (currVal >= prevValue) {
// result += currVal;
// }else{
// result -= currVal;
// }
// prevValue = currVal;
// }
return result;
}
public static void main(String[] args) {
String roman = "XXIV";
int rs = romanToInteger(roman);
System.out.println("Roman To Integer of "+ roman + "is " +rs);
}
}