Skip to content

Commit 2adca41

Browse files
committed
feature: integer to roman
1 parent 1d87426 commit 2adca41

File tree

2 files changed

+125
-0
lines changed

2 files changed

+125
-0
lines changed

code/source/IntegerToRoman.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class IntegerToRoman {
2+
3+
public String intToRoman(int num) {
4+
StringBuilder res = new StringBuilder();
5+
char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
6+
int value[] = {1000, 500, 100, 50, 10, 5, 1};
7+
8+
for (int i = 0; i < 7; i = i + 2) {
9+
int x = num / value[i];
10+
if (x < 4) {
11+
for (int j = 0; j < x; j++) {
12+
res.append(roman[i]);
13+
}
14+
} else if (x == 4) {
15+
res.append(roman[i]).append(roman[i - 1]);
16+
} else if (x < 9) {
17+
res.append(roman[i - 1]);
18+
for (int j = 5; j < x; j++) {
19+
res.append(roman[i]);
20+
}
21+
} else {
22+
res.append(roman[i]).append(roman[i - 2]);
23+
}
24+
num = num % value[i];
25+
}
26+
27+
return res.toString();
28+
}
29+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# 整数转罗马数字
2+
3+
## 日期
4+
5+
2018-11-20
6+
7+
## 题目描述
8+
9+
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
10+
11+
```
12+
字符 数值
13+
I 1
14+
V 5
15+
X 10
16+
L 50
17+
C 100
18+
D 500
19+
M 1000
20+
```
21+
22+
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
23+
24+
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
25+
26+
- I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
27+
- X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
28+
- C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
29+
30+
给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
31+
32+
示例:
33+
34+
```
35+
示例 1:
36+
37+
输入: 3
38+
输出: "III"
39+
示例 2:
40+
41+
输入: 4
42+
输出: "IV"
43+
示例 3:
44+
45+
输入: 9
46+
输出: "IX"
47+
示例 4:
48+
49+
输入: 58
50+
输出: "LVIII"
51+
解释: L = 50, V = 5, III = 3.
52+
示例 5:
53+
54+
输入: 1994
55+
输出: "MCMXCIV"
56+
解释: M = 1000, CM = 900, XC = 90, IV = 4.
57+
```
58+
59+
## 想法
60+
61+
需要判断 <4 =4 <9 =9
62+
63+
## My
64+
65+
```
66+
public class IntegerToRoman {
67+
68+
public String intToRoman(int num) {
69+
StringBuilder res = new StringBuilder();
70+
char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
71+
int value[] = {1000, 500, 100, 50, 10, 5, 1};
72+
73+
for (int i = 0; i < 7; i = i + 2) {
74+
int x = num / value[i];
75+
if (x < 4) {
76+
for (int j = 0; j < x; j++) {
77+
res.append(roman[i]);
78+
}
79+
} else if (x == 4) {
80+
res.append(roman[i]).append(roman[i - 1]);
81+
} else if (x < 9) {
82+
res.append(roman[i - 1]);
83+
for (int j = 5; j < x; j++) {
84+
res.append(roman[i]);
85+
}
86+
} else {
87+
res.append(roman[i]).append(roman[i - 2]);
88+
}
89+
num = num % value[i];
90+
}
91+
92+
return res.toString();
93+
}
94+
}
95+
96+
```

0 commit comments

Comments
 (0)