罗马数字的规则
基本字符 | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
对应的数字 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
- 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
- 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
- 小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
- 正常使用时、连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外);
- 在一个数的上面画一条横线、表示这个数扩大 1000 倍。
自己写的第一个版本
public class No12 {
public static void main(String[] args) {
System.out.println(intToRoman(9));
}
public static String intToRoman(int num) {
String Roman = "";
int M = num / 1000;
num = num % 1000;
for (int i = 0; i < M; i++) {
Roman = Roman + "M";
}
int D = num / 500;
num = num % 500;
if (D == 0) {
int C = num / 100;
num = num % 100;
if (C == 4)
Roman = Roman + "CD";
else
for (int i = 0; i < C; i++) {
Roman = Roman + "C";
}
} else {
int C = num / 100;
num = num % 100;
if (C == 4)
Roman = Roman + "CM";
else {
Roman = Roman + "D";
for (int i = 0; i < C; i++) {
Roman = Roman + "C";
}
}
}
int L = num / 50;
num = num % 50;
if (L == 0) {
int X = num / 10;
num = num % 10;
if (X == 4)
Roman = Roman + "XL";
else
for (int i = 0; i < X; i++) {
Roman = Roman + "X";
}
} else {
int X = num / 10;
num = num % 10;
if (X == 4)
Roman = Roman + "XC";
else {
Roman = Roman + "L";
for (int i = 0; i < X; i++) {
Roman = Roman + "X";
}
}
}
int V = num / 5;
num = num % 5;
if (V == 0) {
int I = num;
if (I == 4)
Roman = Roman + "IV";
else
for (int i = 0; i < I; i++) {
Roman = Roman + "I";
}
} else {
int I = num;
if (I == 4)
Roman = Roman + "IX";
else {
Roman = Roman + "V";
for (int i = 0; i < I; i++) {
Roman = Roman + "I";
}
}
}
return Roman;
}
}
网上看到的第二个版本
public class No12_2 {
public static void main(String[] args) {
System.out.println(intToRoman(1234));
}
public static String intToRoman(int num) {
int[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
String[] str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
"V", "IV", "I" };
String Roman = "";
for (int i = 0; i < nums.length; i++) {
while (num >= nums[i]) {
num = num - nums[i];
Roman = Roman + str[i];
}
}
return Roman;
}
}