目录
一、罗马数字的起源?
二、算法代码
(1)整数转罗马数字算法代码
package learnProject.csdn;
import java.util.Random;
/**
*
* @author Roc-xb
*
*/
public class IntegerToRoman {
private static int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
private static String[] symbols = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
public static String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
int i = 0;
while (num > 0) {
if (num >= values[i]) {
sb.append(symbols[i]);
num -= values[i];
} else {
i++;
}
}
return sb.toString();
}
public static void main(String[] args) {
for (int num = 1; num <= 100; num++) {
// 随机测试
int randomInt = new Random().nextInt(1000);
System.out.println(String.format("整数【%d】用罗马数字表示:%s", randomInt, intToRoman(randomInt)));
}
}
}
(2)罗马数字转整数算法代码
package learnProject.csdn;
public class RomanToInteger {
public static int romanToInt(String s) {
int result = 0;
int prevValue = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
int currValue = getRomanValue(c);
if (currValue < prevValue) {
result -= currValue;
} else {
result += currValue;
}
prevValue = currValue;
}
return result;
}
public static int getRomanValue(char c) {
switch (c) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
public static void main(String[] args) {
String roman = "DCCLXXXVIII";
int num = romanToInt(roman);
System.out.println(String.format("%s罗马数字转换成整数为:%d",roman, num));
}
}