-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
98 lines (87 loc) · 2.5 KB
/
Copy pathRomanToInteger.java
File metadata and controls
98 lines (87 loc) · 2.5 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
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
// Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
// See: https://leetcode.com/problems/roman-to-integer/
package leetcode.math;
import java.util.HashMap;
import java.util.Map;
public class RomanToInteger {
/**
* Solution 2: HashMap solution - cleaner but not faster.
*/
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<>();
map.put('M', 1000);
map.put('D', 500);
map.put('C', 100);
map.put('L', 50);
map.put('X', 10);
map.put('V', 5);
map.put('I', 1);
int prev = 0;
int res = 0;
char[] arr = s.toCharArray();
for (char ch : arr) {
res += map.get(ch);
if (prev < map.get(ch))
res -= 2 * prev;
prev = map.get(ch);
}
return res;
}
/**
* Solution 1: Initial solution
*/
public int romanToInt_var1(String s) {
char prev = '\0';
int res = 0;
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
switch (arr[i]) {
case 'M':
res += 1000;
if (prev == 'C')
res -= 200;
break;
case 'D':
res += 500;
if (prev == 'C')
res -= 200;
break;
case 'C':
res += 100;
if (prev == 'X')
res -= 20;
break;
case 'L':
res += 50;
if (prev == 'X')
res -= 20;
break;
case 'X':
res += 10;
if (prev == 'I')
res -= 2;
break;
case 'V':
res += 5;
if (prev == 'I')
res -= 2;
break;
case 'I':
res += 1;
break;
default:
break;
}
prev = arr[i];
}
return res;
}
public static void main(String[] args) {
RomanToInteger sln = new RomanToInteger();
System.out.println(sln.romanToInt("III"));
System.out.println(sln.romanToInt("IV"));
System.out.println(sln.romanToInt("IX"));
System.out.println(sln.romanToInt("LVIII"));
System.out.println(sln.romanToInt("MCMXCIV"));
}
}