-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomanToInt.java
More file actions
107 lines (98 loc) · 2.28 KB
/
RomanToInt.java
File metadata and controls
107 lines (98 loc) · 2.28 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package collection2;
import java.util.Stack;
/*
* Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*/
public class RomanToInt {
public static int romanToInt(String s) {
/*
* 'I' = 1, 'V' = 5, 'X' = 10, 'L' = 50, 'C' = 100 'D' = 500, 'M' =
* 1000,
*/
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (temp == 'I') {
st.push(1);
} else if (temp == 'V') {
st.push(5);
} else if (temp == 'X') {
st.push(10);
} else if (temp == 'L') {
st.push(50);
} else if (temp == 'C') {
st.push(100);
} else if (temp == 'D') {
st.push(500);
} else if (temp == 'M') {
st.push(1000);
}
}
int last = 0;
int that = 0;
int result = 0;
while (!st.empty()) {
that = st.pop();
if (that >= last) {
result += that;
} else {
result -= that;
}
last = that;
}
return result;
}
public static String intToRoman(int num) {
/*
* 'I' = 1, 'V' = 5, 'X' = 10, 'L' = 50, 'C' = 100 'D' = 500, 'M' =
* 1000,
*/
if(num>=1000){
String temp = "M";
return temp.concat(intToRoman(num-1000));
} else if(num>=500){
String temp = "D";
return temp.concat(intToRoman(num-500));
}else if(num>=400&&num<500){
String temp = "CD";
return temp.concat(intToRoman(num-400));
}
else if(num>=100&&num<=399){
String temp = "C";
return temp.concat(intToRoman(num-100));
} else if(num>=50){
String temp = "L";
return temp.concat(intToRoman(num-50));
}
else if(num>=40&&num<50){
String temp = "XL";
return temp.concat(intToRoman(num-40));
}
else if(num>=10&&num<=39){
String temp = "X";
return temp.concat(intToRoman(num-10));
} else if(num>=9&&num<10){
String temp = "IX";
return temp.concat(intToRoman(num-9));
}
else if(num>=5){
String temp = "V";
return temp.concat(intToRoman(num-5));
}
else if(num>=4&&num<5){
String temp = "IV";
return temp.concat(intToRoman(num-4));
}
else if(num>=1&&num<=3){
String temp = "I";
return temp.concat(intToRoman(num-1));
}
return "";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(romanToInt("XXXI"));
System.out.println(intToRoman(19));
}
}