你如何找到相当于整数的罗马数字 [英] How do you find a roman numeral equivalent of an integer

查看:141
本文介绍了你如何找到相当于整数的罗马数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you find a roman numeral equivalent of an integer. Is there a java library which provides this capability?

我找到了类似的问题,但我更喜欢这个问题的开箱即用的API抽象。处理代码中的所有可能组合真的很痛苦。

I did find a similar question, but I would prefer an out of the box API abstraction for this issue. Its just painful to handle all possible combinations in your code.

推荐答案

这是一个链接,适用于包括Java在内的多种语言。以下是相关摘录:

Here is a link for many languages including Java. Here's an extract of relevance:

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);
    }

}

这篇关于你如何找到相当于整数的罗马数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆