leetcode-12 整数转罗马数字

题目分析

使用贪心法去做,罗马数字就是尽可能的使用大数表示,那么我们从大到小安排数字就可以了。

Java代码

public String intToRoman(int num) {
        StringBuffer sb = new StringBuffer();
        String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int[] nums = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
        int index = 0;
        while(index<13){
            while(num>=nums[index]){
                sb.append(romans[index]);
                num -= nums[index];
            }
            index++;
        }
        return sb.toString();
    }

你可能感兴趣的:(LeetCode,贪心算法)