-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintToRoman.java
More file actions
73 lines (68 loc) · 2.15 KB
/
intToRoman.java
File metadata and controls
73 lines (68 loc) · 2.15 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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Author : WindAsMe
* File : intToRoman.java
* Time : Create on 18-5-27
* Location : ../Home/JavaForLeeCode2/intToRoman.java
* Function : LeeCode No.12
*/
public class intToRoman {
// num is in (1, 3999)
private static String intToRomanResult(int num){
// Set to find
Map<Integer, Character> map = new HashMap<>();
map.put(1, 'I');
map.put(5, 'V');
map.put(10, 'X');
map.put(50, 'L');
map.put(100, 'C');
map.put(500, 'D');
map.put(1000, 'M');
StringBuilder s = new StringBuilder();
Stack<Integer> stack = new Stack<>();
int flag = 1;
while (num != 0){
int temp = num % 10;
stack.push(temp * flag);
num /= 10;
flag *= 10;
}
flag /= 10;
System.out.println("Start:" + flag);
while (!stack.empty()){
while (flag != 0){
int temp = stack.pop();
while (temp != 0){
if (temp / flag == 4){
char mark = map.get(flag);
s.append(mark);
mark = map.get(flag * 5);
s.append(mark);
temp = 0;
} else if (temp / flag == 9){
char mark = map.get(flag);
s.append(mark);
mark = map.get(flag * 10);
s.append(mark);
temp = 0;
} else if (temp / flag >= 5){
char mark = map.get(flag * 5);
s.append(mark);
temp -= 5 * flag;
} else {
char mark = map.get(flag);
s.append(mark);
temp -= flag;
}
}
flag = flag / 10;
}
}
return s.toString();
}
public static void main(String[] args){
System.out.println(intToRomanResult(444));
}
}