-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13. Roman to Integer.java
59 lines (56 loc) · 1.22 KB
/
13. Roman to Integer.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
class Solution {
int val(char c)
{
int v = -1;
switch(c)
{
case 'I':
v = 1;
break;
case 'V':
v = 5;
break;
case 'X':
v = 10;
break;
case 'L':
v = 50;
break;
case 'C':
v = 100;
break;
case 'D':
v = 500;
break;
case 'M':
v = 1000;
break;
}
return v;
}
public int romanToInt(String s) {
int res = 0;
for(int i = 0; i < s.length(); i++)
{
int res1 = val(s.charAt(i));
if(i + 1 < s.length())
{
int res2 = val(s.charAt(i+1));
if(res1 >= res2)
{
res += res1;
}
else if(res2 > res1)
{
res += res2 - res1;
i++;
}
}
else
{
res += res1;
}
}
return res;
}
}