如何找到整数的罗马数字等价物

2022-09-02 04:03:35

如何找到等效于整数的罗马数字。是否有提供此功能的 Java 库?

我确实发现了一个类似的问题,但我更喜欢这个问题的开箱即用API抽象。处理代码中所有可能的组合只是痛苦的。


答案 1

这是包括Java在内的许多语言的链接。以下是相关性的摘录:

public class RN {

    enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {

        if( n <= 0) {
            throw new IllegalArgumentException();
        }

        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }

}

答案 2

这是我正在使用的代码,就在excel列名称转换器旁边。为什么没有一个 apache 库来做这些东西呢?

private static final char[] R = {'ↂ', 'ↁ', 'M', 'D', 'C', 'L', 'X', 'V', 'I'};
// or, as suggested by Andrei Fierbinteanu
// private static final String[] R = {"X\u0305", "V\u0305", "M", "D", "C", "L", "X", "V", "I"};
private static final int MAX = 10000; // value of R[0], must be a power of 10

private static final int[][] DIGITS = {
    {},{0},{0,0},{0,0,0},{0,1},{1},
    {1,0},{1,0,0},{1,0,0,0},{0,2}};

public static String int2roman(int number) {
    if (number < 0 || number >= MAX*4) throw new IllegalArgumentException(
            "int2roman: " + number + " is not between 0 and " + (MAX*4-1));
    if (number == 0) return "N";
    StringBuilder sb = new StringBuilder();
    int i = 0, m = MAX;
    while (number > 0) {
        int[] d = DIGITS[number / m];
        for (int n: d) sb.append(R[i-n]);
        number %= m;
        m /= 10;
        i += 2;
    }
    return sb.toString();
}

编辑:

现在我再看一遍,循环可以浓缩为

    for (int i = 0, m = MAX; m > 0; m /= 10, i += 2) {
        int[] d = DIGITS[(number/m)%10];
        for (int n: d) sb.append(R[i-n]);
    }

使代码的可读性更差;-)


推荐