13.Roman Into Integer

Question:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Hints:

Hint-1:

I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000

Hint-2:

  • If I comes before V or X, subtract 1 eg: IV = 4 and IX = 9
  • If X comes before L or C, subtract 10 eg: XL = 40 and XC = 90
  • If C comes before D or M, subtract 100 eg: CD = 400 and CM = 900

My Answer:

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
class Solution {
public int romanToInt(String s) {
int len = s.length();
int res = 0;
for(int i=0;i<len;i++){
char temp = s.charAt(i);
switch(temp){
case 'I':
System.out.println(i);
System.out.println(temp);
if(i <= len-2 && s.charAt(i+1) == 'V'){
res = res + 4;
i = i + 1;
System.out.println(i);
System.out.println(res);
}
else if(i <= len-2 && s.charAt(i+1) == 'X'){
res = res + 9;
i = i + 1;
}
else{
res = res + 1;
System.out.println(i);
System.out.println(res);
}
System.out.println(res);
break;
case 'V':
res = res + 5;
break;
case 'X':
if(i <= len-2 && s.charAt(i+1) == 'L'){
res = res + 40;
i = i + 1;
}
else if(i <= len-2 && s.charAt(i+1) == 'C'){
res = res + 90;
i = i + 1;
}
else{
res = res + 10;
}
break;
case 'L':
res = res + 50;
break;
case 'C':
if(i <= len-2 && s.charAt(i+1) == 'D'){
res = res + 400;
i = i + 1;
}
else if(i <= len-2 && s.charAt(i+1) == 'M'){
res = res + 900;
i = i + 1;
}
else{
res = res + 100;
}
break;
case 'D':
res = res + 500;
break;
case 'M':
res = res + 1000;
break;
}
}
return res;
}
}

I just know basic about java, so I only use sample logic.

Sorry about that.

Runtime: 300ms

Better Answers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int romanToInt(String s) {
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 len = s.length();
int sum = map.get(s.charAt(len - 1));
for (int i = len - 2; i >= 0; --i) {
if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
sum -= map.get(s.charAt(i));
} else {
sum += map.get(s.charAt(i));
}
}
return sum;
}
}

Runtime: 149ms

Here use map HashMap, speed up~