leetCode 12 整數转罗马数字

原题点这里

直接暴力模拟 6ms

public static String getOne(int num,int e){

        String ans = null;
        switch (num){
            case 0: ans= "";
                    break;
            case 1: ans= "I";break;
            case 2: ans= "II";break;
            case 3: ans= "III";break;
            case 4: ans= "IV";break;
            case 5: ans= "V";break;
            case 6: ans= "VI";break;
            case 7: ans= "VII";break;
            case 8: ans= "VIII";break;
            case 9: ans= "IX";break;
        }

        if(e==0) return ans;
        if(e==1) {
            ans=ans.replace('X','C');
            ans=ans.replace('V','L');
            ans=ans.replace('I','X');
            return ans;
        }
        if(e==2){
            ans=ans.replace('X','M');
            ans=ans.replace('V','D');
            ans=ans.replace('I','C');
            return ans;
        }
        ans = ans.replace('I','M');

        return ans;
    }
View Code

 

也可以用贪心的算法

    public static String intToRoman2(int num) {
        int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int ind =0;
        StringBuilder ans = new StringBuilder("");
        while (ind<13){
            while (num>=nums[ind]){

                ans.append(romans[ind]);
                num-=nums[ind];
            }
            ind++;

        }
        return ans.toString();
    }
View Code

 

posted @ 2020-03-31 20:52  超级学渣渣  阅读(126)  评论(0编辑  收藏  举报