Integer to Roman

题目描述:

Given an integer, convert it to a roman numeral.

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

【罗马数字】

1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.

代码如下:

public class Solution {
    public String intToRoman(int num) {
        String result="";
        int i=0;
        String[][] strs=new String[][]{{"I","V"},{"X","L"},{"C","D"},{"M"}};
        while(num!=0){
            result=getRoman(num%10,i,strs)+result;
            num/=10;i++;
        }
        return result;
    }
    
    public String getRoman(int n,int i,String[][] strs){
        String str="";
        switch (n) {
            case 1:str=strs[i][0];break;
            case 2:str=strs[i][0]+strs[i][0];break;
            case 3:str=strs[i][0]+strs[i][0]+strs[i][0];break;
            case 4:str=strs[i][0]+strs[i][1]+str;break;
            case 5:str=strs[i][1];break;
            case 6:str=strs[i][1]+strs[i][0];break;
            case 7:str=strs[i][1]+strs[i][0]+strs[i][0];break;
            case 8:str=strs[i][1]+strs[i][0]+strs[i][0]+strs[i][0];break;
            case 9:str=strs[i][0]+strs[i+1][0];break;
        default:
            break;
        }
        return str;
    }
}


你可能感兴趣的:(java,Math,LeetCode)