罗马数和数字互转
2018-12-10 本文已影响0人
小诸葛686
1.罗马数是什么
2.罗马数和数字互转
import java.util.HashMap;
import java.util.Map;
public class Test {
//正确的规则集合,存储了罗马数和阿拉伯数字映射
public final static Map<String, Integer> maps = new HashMap<>();
//阿拉伯数字和罗马数字对应的关系
public final static String[] ones = new String[]{"I","II","III","IV","V","VI","VII","VIII","IX"};
public final static String[] tens = new String[]{"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
public final static String[] hundreds = new String[]{"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
public final static String[] thousands = new String[]{"M","MM","MMM"};
static {
//罗马和阿拉伯关系
maps.put("I", 1);
maps.put("V", 5);
maps.put("X", 10);
maps.put("L", 50);
maps.put("C", 100);
maps.put("D", 500);
maps.put("M", 1000);
}
/**
* 解析罗马数
* 描述:先转换罗马数组为阿拉伯数组,便于比较大小,然后根据罗马数规则算出阿拉伯规格对应值
* 处理思路:
* 数组从左往右循环,从当前元素开始右移,直到下一个值比当前值小才结束,表示开始位置到当前位置为一个值
* 例如:IIIXI中IIIX是一个值
*
* 注:例子中只针对有效罗马数字转换成阿拉伯数字及从大到小组合的罗马数,不支持类似CMM,必须写成MCM
* @param roman
* @return
* @throws Exception 当字符不在我们定义的关系映射中会抛出异常
*/
public static Integer parseRoman(String roman) throws Exception {
char[] chars = roman.toCharArray();
int[] nums = new int[chars.length];
for(int i = 0;i < chars.length;i ++){
nums[i] = maps.get(String.valueOf(chars[i]));
}
int sum = 0;
int start = 0;
//判断是否出现了较小的值先于较大的值
boolean flag = false;
for(int i = 0;i < nums.length;i ++){
start = i;
flag = false;
while(true){
if(i + 1 >= nums.length || nums[i] > nums[i + 1]){
if(nums[i] > nums[start]){
flag = true;
}
sum = sum + nums[i];
for(;start <= i - 1;start ++){
if(flag){
sum = sum - nums[start];
}else{
sum = sum + nums[start];
}
}
break ;
}
i ++;
}
}
return sum;
}
/**
* 分解number 例如1234分解成1000 + 200 + 30 + 4 = M + CC + XXX + IIII
* @param number
* @return
*/
public static String parseNumber(Integer number){
if(number == null || number <= 0) return "";
if(number > 3999){
throw new RuntimeException("超出范围");
}
StringBuilder sb = new StringBuilder();
int one = number%10;
int ten = number/10%10;
int hundred = number/100%10;
int thousand = number/1000%10;
sb.append(thousand > 0?thousands[thousand - 1]:"");
sb.append(hundred > 0?hundreds[hundred - 1]:"");
sb.append(ten > 0?tens[ten - 1]:"");
sb.append(one > 0?ones[one - 1]:"");
return sb.toString();
}
/**
* 测试结果和性能
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
int num = 10000;
while(num > 0){
for(int i = 0;i < 3999;i ++){
int result = parseRoman(parseNumber(i));
if(i != result){
System.out.println(false);
}
}
num --;
}
System.out.println(System.currentTimeMillis() - start);
}
}