-
Notifications
You must be signed in to change notification settings - Fork 0
/
RomanToInteger.java
106 lines (90 loc) · 2.83 KB
/
RomanToInteger.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package LeetCodeBasic;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author Srinvas Vadige, [email protected]
* @since 21 Sept 2024
*/
public class RomanToInteger {
public static void main(String[] args) {
String romanNum = "DCXXI";
System.out.println(romanToIntApproach1(romanNum));
System.out.println(romanToIntApproach2(romanNum));
}
// @SuppressWarnings("unchecked")
public static int romanToIntApproach1(String s) {
// @SuppressWarnings("rawtypes")
HashMap<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;
for(int i=0; i<s.length(); i++){
int charValue = map.get(s.charAt(i));
int nextCharValue = i+1<s.length()? map.get(s.charAt(i+1)): 0;
result = result + (charValue<nextCharValue? -charValue: +charValue); // IV, IX, XL, XC.....
// // or skip nextChar itertion
// if (charValue < nextCharValue){
// charValue = nextCharValue - charValue;
// i++;
// }
// result += charValue;
}
return result;
}
public static int romanToIntApproach2(String s) {
//IV
//IX
//XL
//XC
//CD
//CM
// M D C L X V I
int sum = 0;
for(int i=0; i<s.length(); i++){
char charAtIndex = s.charAt(i);
int charValue = getRomanValue(charAtIndex);
if(Arrays.asList('I', 'X', 'C').contains(charAtIndex) && i<s.length()-1){
if(shouldSkipNextChar(charAtIndex, s.charAt(i+1))){
charValue = getRomanValue(s.charAt(i+1)) - charValue;
i++;
}
}
sum += charValue;
}
return sum;
}
public static boolean shouldSkipNextChar(char c, char nextChar ){
if(c == 'I' && Arrays.asList('V','X').contains(nextChar)
|| c == 'X' && Arrays.asList('L','C').contains(nextChar)
|| c == 'C' && Arrays.asList('D','M').contains(nextChar)
)
return true;
return false;
}
public static int getRomanValue(char c){
int value;
switch(c){
case 'I': value = 1;
break;
case 'V': value = 5;
break;
case 'X': value = 10;
break;
case 'L': value = 50;
break;
case 'C': value = 100;
break;
case 'D': value = 500;
break;
case 'M': value = 1000;
break;
default: value = 0;
}
return value;
}
}