-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
81 lines (75 loc) · 2.67 KB
/
RomanToInteger.java
File metadata and controls
81 lines (75 loc) · 2.67 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
74
75
76
77
78
79
80
81
public class RomanToInteger {
public static void main(String[] args) {
String a="1";
while (a!="0") {
System.out.println("Enter the Romanletter below 3999");
Scanner scanner=new Scanner(System.in);
String s=scanner.nextLine();
System.out.println(romanToInt(s));
System.out.println("Enter 1 to continue 0 to exit");
a=scanner.nextLine();
}
}
public static int romanToInt(String s){
s=s.toUpperCase();
int result=0;
String temp="";
String[] oneDigit={"","I","II","III","IV","V","VI","VII",
"VIII","IX"};
String[] twoDigits={"","X","XX","XXX","XL","L","LX","LXX",
"LXXX","XC"};
String[] threeDigits={"","C","CC","CCC","CD","D","DC","DCC",
"DCCC","CM"};
String[] fourDigits={"","M","MM","MMM","MMMM"};
// to get single digit Int for the given Roman
for (int j = 0; j <oneDigit.length; j++) {
if (s.equals(oneDigit[j])){
result=j;
return result;
}
}
//To get ten'th digit Int for the given Roman
for (int i = 0; i <s.length() ; i++) {
temp = s.substring(0, s.length() - i);
for (int j = 0; j < twoDigits.length; j++) {
if (temp.equals(twoDigits[j])) {
result = (j * 10);
break;
}
}
if (result > 0){
String temp2=s.substring(temp.length());
return result + romanToInt(temp2);
}
}
// three digits
for (int i = 0; i <s.length() ; i++) {
temp = s.substring(0, s.length() - i);
for (int j = 0; j < threeDigits.length; j++) {
if (temp.equals(threeDigits[j])) {
result = (j * 100);
break;
}
}
if (result > 0){
String temp3=s.substring(temp.length());
return result + romanToInt(temp3);
}
}
//fourth
for (int i = 0; i <s.length() ; i++) {
temp = s.substring(0, s.length() - i);
for (int j = 0; j < fourDigits.length; j++) {
if (temp.equals(fourDigits[j])) {
result = (j * 1000);
break;
}
}
if (result > 0){
String temp4=s.substring(temp.length());
return result + romanToInt(temp4);
}
}
return 0;
}
}