LeetCode-第十二题:Integer to Roman

题目

LeetCode-第十二题:Integer to Roman_第1张图片
十二题.png

题目十分简单,就是将阿拉伯数字转换为罗马数字。此题的要点在于理解罗马数字的表示规则。而该规则在百度百科说的十分清楚(罗马数字)

分析

明白了罗马数字的表示规则之后,此题就很简单了。并且由题目可知最大为3999。这就意味着可以用一个二维数组将所有的情况简单的列出来,如下所示:

String[][] nn={{"","I","II","III","IV","V","VI","VII","VIII","IX"},
                      {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
                      {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
                      {"","M","MM","MMM"}};

分别对应个位的1-9,十位的10-90,百位的100-900,千位的1000-3000。然后根据求得的值从数组中取得相应的值来连接字符串,生成结果。如1204,1204/1000=1,取出对应的“M”;204/100=2,2取出对应的“CC“;0/10=0,取出对应的“”;4/1=4,取出对应的“IV“。然后将这几个字符串连接起来即是结果:“MCCIV”。

代码

代码为Java版,如下:

public class Solution 
{
    public String intToRoman(int num) 
    {
        String[][] nn={{"","I","II","III","IV","V","VI","VII","VIII","IX"},
                {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
                {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
                {"","M","MM","MMM"}};
        int temp=num/1000;
        String result=nn[3][temp];
        num-=temp*1000;

        temp=num/100;
        result+=nn[2][temp];
        num-=temp*100;

        temp=num/10;
        result+=nn[1][temp];
        num-=temp*10;

        temp=num;
        result+=nn[0][temp];

        return result;
    }
}

你可能感兴趣的:(LeetCode-第十二题:Integer to Roman)