12. Integer to Roman

本文介绍了一种使用递归方法将整数转换为罗马数字的算法,并提供了详细的Java代码实现。该方法适用于1到3999范围内的整数转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Subscribe to see which companies asked this question.


Solution:

Tips:

solve this problem with recursion, just for practice.


Java Code:

public class Solution {
    public String intToRoman(int num) {
        if (num <= 0) {
            return "";
        }
        
        if (num >= 900) {
            return num >= 1000 ? "M" + intToRoman(num - 1000) : "CM" + intToRoman(num - 900);
        } else if (num >= 400) {
            return num >= 500 ? "D" + intToRoman(num - 500) : "CD" + intToRoman(num - 400);
        } else if (num >= 90) {
            return num >= 100 ? "C" + intToRoman(num - 100) : "XC" + intToRoman(num - 90);
        } else if (num >= 40) {
            return num >= 50 ? "L" + intToRoman(num - 50) : "XL" + intToRoman(num - 40);
        } else if (num >= 9) {
            return num >= 10 ? "X" + intToRoman(num - 10) : "IX" + intToRoman(num - 9);
        } else if (num >= 4) {
            return num >= 5 ? "V" + intToRoman(num - 5) : "IV" + intToRoman(num - 4);
        } else {
            return "I" + intToRoman(num - 1);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值