• 第12题 数字转为罗马数字


    罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。

    一开始我按照10进制的思想来做,针对不同区间,编辑不同的罗马表达方式,比如1~9,10~90,100~900,1000~3000

    以下是代码:

    public static String intToRoman(int num) {
            
            //
            String roman = "";
            if(num<=0) return "";
            if(num<=10){
                String[] tens = new String[]{"I","II","III","IV","V","VI","VII","VIII","IX","X"};
                roman = roman+tens[num-1];
                
            }
            if(10<num && num<100){ //90以内都可以用I V X L表示
                String[] ten2nines = new String[] {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; //10,20,30,40,50,60,70,80
                int H = ((int) (num/10));
                int L = num-H*10;
                roman = roman + ten2nines[H-1] + intToRoman(L);
            }
            
            if(100<=num && num<1000){
                String[] len = new String[] {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};//100,200,300,400,500,600,700,800,900
                int H = ((int) (num/100));
                int L = num-H*100;
                roman = roman + len[H-1] + intToRoman(L);
            }
            if(1000<=num && num <4000){
                String[] len = new String[] {"M","MM","MMM"};
                int H = ((int) (num/1000));
                int L = num-H*1000;
                System.out.println("H:"+H+",L:"+L);
                roman = roman + len[H-1] + intToRoman(L);
            }
            return roman;
        }

    后来看到网上有一个简便的,先找到所有罗马数字的基,对于十进制,基为(1,2,3,4,5,6,7,8,9,10),罗马数字的基为("M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"),对应数字(1000,900,500,400,100,90,50,40,10,9,5,4,1)

    以下为代码:

    public static String intToRoman(int num) {
            String data[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
            int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}, base = -1;
            StringBuilder result = new StringBuilder();
    
            for(int i = 0;i < data.length;i++){
                if((base=num/value[i])!=0){
                    while(base--!=0) result.append(data[i]);
                    num=num%value[i];
                }
            }
            return result.toString();
    }
  • 相关阅读:
    看过设计模式第一章的心得
    支付宝支付过程填坑
    C# 合并只要有交集的所有集合
    C#中的反射 Reflection
    动态更改配置文件
    六种弹窗
    Respone弹窗
    Aspose是一个很强大的控件,可以用来操作word,excel,ppt等文件
    使用ECharts报表统计公司考勤加班,大家加班多吗?
    排污许可管理条例-中华人民共和国国务院令第736号
  • 原文地址:https://www.cnblogs.com/wuchaodzxx/p/5852385.html
Copyright © 2020-2023  润新知