zoukankan      html  css  js  c++  java
  • 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();
    }

  • 相关阅读:
    写诊股广告页面遇到的问题
    移动端web页面滚动不流畅,卡顿闪烁解决方案
    用JS和JQ来获取子节点!
    CSS样式表的写作规范
    常用css3
    移动端引用echarts的折线图
    JS----获取DOM元素的方法(8种)
    随机对决
    字体
    Echarts个性化图表的样式--绘制南丁格尔图
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6497341.html
Copyright © 2011-2022 走看看