-
Notifications
You must be signed in to change notification settings - Fork 4
/
13. Roman to Integer
39 lines (39 loc) · 1.02 KB
/
13. Roman to Integer
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
//O(n) time and space
class Solution {
public int romanToInt(String s) {
int[] digits = new int[s.length()];
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case 'I':
digits[i] = 1;
break;
case 'V':
digits[i] = 5;
break;
case 'X':
digits[i] = 10;
break;
case 'L':
digits[i] = 50;
break;
case 'C':
digits[i] = 100;
break;
case 'D':
digits[i] = 500;
break;
case 'M':
digits[i] = 1000;
break;
}
}
int result = 0;
for(int i=0;i<digits.length-1;i++){
if(digits[i]<digits[i+1])
result-=digits[i];
else
result+=digits[i];
}
return result+digits[s.length()-1];
}
}