leetcode-12-java

问题:12. Integer to Roman

1
2
3
4
5
6
7
8
9
10
11
12
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II.
The number twenty seven is written as XXVII, which is XX + V + II

leetcode地址

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
class Solution {
private static List<Point> list = new ArrayList<Point>(){{
add(new Point(1000, "M"));
add(new Point(900, "CM"));
add(new Point(500, "D"));
add(new Point(400, "CD"));
add(new Point(100, "C"));
add(new Point(90, "XC"));
add(new Point(50, "L"));
add(new Point(40, "XL"));
add(new Point(10, "X"));
add(new Point(9, "IX"));
add(new Point(5, "V"));
add(new Point(4, "IV"));
add(new Point(1, "I"));
}
};
public static String intToRoman(int num) {

int index = 0;
StringBuffer sb = new StringBuffer();
while (num != 0) {
Point point = list.get(index);
if (num - point.getBase() >= 0) {
sb.append(point.getDesc());
num -= point.getBase();
} else {
index ++;
}
}
return sb.toString();
}

private static class Point {
private Integer base;

private String desc;

private Point(Integer base, String desc) {
this.base = base;
this.desc = desc;
}

public Integer getBase() {
return base;
}

public void setBase(Integer base) {
this.base = base;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}
}
}