LeetCode(12.整数からローマ数字へ)
2818 ワード
アルゴリズムの説明:
アルゴリズムの実装:
Java実装:
: I, V, X, L,C,D M。
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
, 2 II , 1。12 XII , X + II 。 27 XXVII, XX + V + II 。
, 。 , 4 IIII, IV。 1 5 , 5 1 4 。 , 9 IX。 :
I V (5) X (10) , 4 9。
X L (50) C (100) , 40 90。
C D (500) M (1000) , 400 900。
, 。 1 3999 。
1:
: 3
: "III"
2:
: 4
: "IV"
3:
: 9
: "IX"
4:
: 58
: "LVIII"
: C = 100, L = 50, XXX = 30, III = 3.
5:
: 1994
: "MCMXCIV"
: M = 1000, CM = 900, XC = 90, IV = 4.
アルゴリズムの実装:
Java実装:
class Solution {
public String intToRoman(int num) {
StringBuilder res = new StringBuilder();
while (num > 0) {
if (num > 999) { // 1000-3999
int m = num / 1000;
for (int i = 0; i < m; i++) {
res.append("M");
}
num = num - 1000 * m;
} else if (num > 899) { // 900-999
res.append("CM");
num = num - 900;
} else if (num > 499) { // 500-899
res.append("D");
num = num - 500;
} else if (num > 399) { // 400-499
res.append("CD");
num = num - 400;
} else if (num > 99) { // 100-399
res.append("C");
num = num - 100;
} else if (num > 89) { // 90-99
res.append("XC");
num = num - 90;
} else if (num > 49) { // 50-89
res.append("L");
num = num - 50;
} else if (num > 39) { // 40-49
res.append("XL");
num = num - 40;
} else if (num > 9) { // 10-39
res.append("X");
num = num - 10;
} else if (num > 8) { // 9
res.append("IX");
break;
} else if (num > 4) { // 5-8
res.append("V");
num = num - 5;
} else if (num > 3) { // 4
res.append("IV");
num = num - 4;
} else { // 1-3
for (int i = 0; i < num; i++) {
res.append("I");
}
break;
}
}
return res.toString();
}
}