-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRomanToInteger.java
83 lines (73 loc) · 1.86 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
public class RomanToInteger {
public static void main(String[]args){
System.out.print(romanToint("IV"));
}
static int romanToint(String s){/*
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
*/
int value=0;
char [] stringArray= s.toCharArray();
for(int i=0;i<stringArray.length;i++){
switch(stringArray[i]){
case 'I':
if(i<stringArray.length-1 && stringArray[i+1]=='V'){
value=value+4;
i=i+1;
}
else if(i<stringArray.length-1 && stringArray[i+1]=='X'){
value=value+9;
i=i+1;
}
else{
value=value+1;
}
break;
case 'V':
value=value+5;
break;
case'X':
if(i<stringArray.length-1 && stringArray[i+1]=='L'){
value=value+40;
i=i+1;
}
else if(i<stringArray.length-1 && stringArray[i+1]=='C'){
value=value+90;
i=i+1;
}
else{
value=value+10;
}
break;
case 'L':
value=value+50;
break;
case'C':
if(i<stringArray.length-1 && stringArray[i+1]=='D'){
value =value+400;
i=i+1;
}
else if(i<stringArray.length-1 && stringArray[i+1]=='M'){
value=value+900;
i=i+1;
}
else{
value=value+100;
}
break;
case'D':
value=value+500;
break;
case'M':
value=value+1000;
break;
}
}
return value;
}
}