LeetCode题解-12-Integer to Roman

解题思路

题意是说把1~3999之间的数字转成罗马数字。

首先要理解罗马数字的表示法,它是按大小结合顺序来的,前面几个字母组合起来如果能够解释成较大的数字,那就使用这个表示,而不是按举个字母来的。

所以数字转成罗马数字,就可以从字母可以表示的最大数字开始,每找到一个就是增加对应的罗马数字,并记录对剩余部分数字匹配,直到这个罗马数字过大,再取一个较小的继续尝试。

参考源码

public class Solution {
    private static String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    private static int[] ints = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

    public String intToRoman(int num) {
        int pos = 0;
        StringBuilder sb = new StringBuilder();
        while (num != 0) {
            if (num >= ints[pos]) {
                num -= ints[pos];
                sb.append(romans[pos]);
            } else {
                pos++;
            }
        }
        return sb.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/mccxj/article/details/60351354
今日推荐