【LeetCode】12. Integer to Roman(中等难度)

【LeetCode】12. Integer to Roman(中等难度)
【LeetCode】12. Integer to Roman(中等难度)

解法一

主要思想就是每次取出⼀位,然后得到相应的罗⻢数字,然后合起来就⾏。

class Solution {
    public String getRoman(int num, int count){ { //count 表示当前的位数,个位,⼗位...
        char[] ten = {'I', 'X', 'C', 'M'};
        char[] five = {'V', 'L', 'D'};
        String r = "";
        if(num <= 3){
            while(num != 0){
                r += ten[count];
                num--;
            }
        }
        if(num == 4){
            r = ten[count] + "" + five[count] + "";
        }
        if(num == 5){
            r = five[count] + "";
        }
        if(num > 5 && num < 9){
            r = five[count] + "";
            num -= 5;
            while(num != 0){
                r += ten[count];
                num--;
            }
        }
        if(num == 9){
            r = ten[count] + "" + ten[count + 1] + "";
        }
        return r;
    }

    public String intToRoman(int num) {
        String r = "";
        int count = 0;
        while(num != 0){
            int pop = num % 10;
            r = getRoman(pop, count) + r;
            count++;
            num /= 10;
        }
        return r;
    }
}

解法二

把所有的组合列出来,因为罗⻢数字表示的⼤⼩就是把所有字⺟相加,所以每次
append 那个,再把对应的值减去就⾏了。

class Solution {
    public String intToRoman(int num) {
        int[] values = {1000, 900, 500c, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<values.length; i++){
            while(num >= values[i]){
                num -= values[i];
                sb.append(strs[i]);
            }
        }
        return sb.toString();
    }
}
上一篇:使用RTX3080显卡搭建基于Pycharm+Python+Cuda+cuDNN+TensorFlow的深度学习开发环境


下一篇:网络 | Linux ping任何ip均出现 Destination Host Unreachable 排查思路与方法