-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathRomanNumerals.java
More file actions
73 lines (61 loc) · 1.92 KB
/
Copy pathRomanNumerals.java
File metadata and controls
73 lines (61 loc) · 1.92 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
public class RomanNumerals {
public int convertToInteger(String romanNum) throws RomanNumeralsException {
int length=romanNum.length();
int i=0;
int number = 0;
if (romanNum.indexOf("IIII") >= 0)
throw new RomanNumeralsException("More than three I's in row is not accepted.");
else if (romanNum.indexOf("XXXX") >= 0)
throw new RomanNumeralsException("More than three X's in row is not accepted.");
else if (romanNum.indexOf("CCCC") >= 0)
throw new RomanNumeralsException("More than three C's in row is not accepted.");
else if (romanNum.indexOf("MMMM") >= 0)
throw new RomanNumeralsException("More than three M's in row is not accepted.");
if (romanNum.indexOf("VV") >= 0)
throw new RomanNumeralsException("More than two V's in row is not accepted.");
else if (romanNum.indexOf("LL") >= 0)
throw new RomanNumeralsException("More than two L's in row is not accepted.");
else if (romanNum.indexOf("DD") >= 0)
throw new RomanNumeralsException("More than two D's in row is not accepted.");
// todo: two or more smaller before big results exception
while(i<length)
{
if ((i+1)<length && valueOfLetter(romanNum.charAt(i)) < valueOfLetter(romanNum.charAt(i+1))){
number += valueOfLetter(romanNum.charAt(i+1)) - valueOfLetter(romanNum.charAt(i));
i+=2;
}
else {
number += valueOfLetter(romanNum.charAt(i));
i++;
}
}
return number;
}
private int valueOfLetter(Character letter) {
int number = 0;
switch (letter) {
case 'I':
number = 1;
break;
case 'V':
number = 5;
break;
case 'X':
number = 10;
break;
case 'L':
number = 50;
break;
case 'C':
number = 100;
break;
case 'D':
number = 500;
break;
case 'M':
number = 1000;
break;
}
return number;
}
}