Intger To Roman

这题意思是将一个输入的整型阿拉伯数字转化为罗马数字。

思路是将1-10对应的罗马数字放在字符串数组里,然后发现数据变化规律即可,eg:389 = 300 + 89 +9 分别对应的罗马数字。

public static void main(String[] args) {
  String[] strs = {"I","II","III","IV","V","VI","VII","VIII","IX","X"};
  Scanner input = new Scanner(System.in);
  System.out.print("请输入一个1-3999整数:");
  int n = input.nextInt();
  if(n < 1 || n >3999){
    System.out.print("输入超出范围!");
  }else{
    String result = toRomanNumeral(strs,n);
    System.out.println(result);
  }
}
public static String toRomanNumeral(String[] strs, int n) {
  StringBuffer sb = new StringBuffer();
  if(n > 0 && n <= 10){
    sb.append(strs[n-1]);
  }else if(n>10 && n <=100){
    sb.append(zhuanHua(n/10,strs)).append(strs[n%10-1]);
  }else if(n>100 && n <= 1000){
    sb.append(zhuanHua2(n/100,strs)).append(zhuanHua(n%100/10,strs)).append(strs[n%100%10-1]);
  }else if(n>1000 && n <= 3999){
    for(int i = 0; i < n/1000; ++i){
      sb.append("M");
    }
    n%=1000;
    sb.append(zhuanHua2(n/100,strs)).append(zhuanHua(n%100/10,strs)).append(strs[n%100%10-1]);
  }else{
    sb.append("输入超出范围!");
  }
  return sb.toString();
}
public static String zhuanHua2(int i, String[] strs) {
  StringBuffer sb = new StringBuffer();
  for(int j = 0; j < strs[i-1].length(); ++j){
    char temp = strs[i-1].charAt(j);
    if(temp == 'X'){
      temp = 'M';
    }else if(temp == 'I'){
      temp = 'C';
    }else if(temp == 'V'){
      temp = 'D';
    }
    sb.append(temp);
  }
  return sb.toString();
}
public static String zhuanHua(int i, String[] strs) {
  StringBuffer sb = new StringBuffer();
  for(int j = 0; j < strs[i-1].length(); ++j){
    char temp = strs[i-1].charAt(j);
    if(temp == 'X'){
      temp = 'C';
    }else if(temp == 'I'){
      temp = 'X';
    }else if(temp == 'V'){
      temp = 'L';
    }
    sb.append(temp);
  }
  return sb.toString();
}

posted on 2017-03-03 16:32  蒋闯  阅读(207)  评论(0编辑  收藏  举报