Leetcode 12——Integer to Roman

Posted 真的是从入门开始

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 12——Integer to Roman相关的知识,希望对你有一定的参考价值。

12.Integer to Roman

  Given an integer, convert it to a roman numeral.

  Input is guaranteed to be within the range from 1 to 3999.

  拿到题目,分析,比较简单,除掉相应的基数单位,拼接起来就可以,不过要注意4,9这些特殊的表示。

先上我的代码吧;

public String intToRoman(int num){
        StringBuffer sb=new StringBuffer();
        
        while(num!=0){
            if(num>=1000){
                append(sb, "M", num/1000);
                num=num%1000;
            }else if(num>=500){
                if(num>=900){
                    append(sb,"CM",1);
                    num=num-900;
                }else{
                    append(sb,"D",num/500);
                    num=num%500;
                }
            }else if(num>=100){
                if(num>=400){
                    append(sb,"CD",1);
                    num=num-400;
                }else{
                    append(sb,"C",num/100);
                    num=num%100;
                }
            }else if(num>=50){
                if(num>=90){
                    append(sb, "XC", 1);
                    num=num-90;
                }else{
                    append(sb,"L",num/50);
                    num=num%50;
                }
            }else if(num>=10){
                if(num>=40){
                    append(sb,"XL",1);
                    num=num-40;
                }else{
                    append(sb,"X",num/10);
                    num=num%10;
                }
            }else if(num>=5){
                if(num>=9){
                    append(sb,"IX",1);
                    num=num-9;
                }else{
                    append(sb,"V",num/5);
                    num=num%5;
                }
            }else{
                if(num==4){
                    append(sb,"IV",1);
                    num=num-4;
                }else{
                    append(sb,"I",num);
                    num=0;
                }
            }
        }
        return sb.toString();
    }
    public static void append(StringBuffer sb,String str,int times){
        for(int i=0;i<times;i++){
            sb.append(str);
        }
    }

但是呢,当我A掉之后,再去看这上面的第一个答案,跪了,又快又简单。用数组表示要放的数字。

public static String intToRoman(int num) {
    String M[] = {"", "M", "MM", "MMM"};
    String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}

 

以上是关于Leetcode 12——Integer to Roman的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode12 Integer to Roman

LeetCode12. Integer to Roman

LeetCode 12 Integer to Roman (整数转罗马数字)

[LeetCode] 12. Integer to Roman ☆☆

LeetCode(12) - Integer to Roman

LeetCode 12. Integer to Roman