LeetCode 012 Integer to Roman

本文介绍了一种将整数转换为罗马数字的方法,并提供了一个具体的Java实现案例。文章详细解释了罗马数字的基本规则,包括特殊组合的减法规则,并通过一个类和方法展示了如何将1到3999之间的整数转换成相应的罗马数字形式。

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

Roman numerals are represented by seven different symbols: IVXLCD and M.

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

class Solution {
    public String intToRoman(int num) {
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(new Integer(1), "I");map.put(new Integer(2), "II");map.put(new Integer(3), "III");map.put(new Integer(4), "IV");map.put(new Integer(5), "V");map.put(new Integer(6), "VI");map.put(new Integer(7), "VII");map.put(new Integer(8), "VIII");map.put(new Integer(9), "IX");
        map.put(new Integer(10), "X");map.put(new Integer(20), "XX");map.put(new Integer(30), "XXX");map.put(new Integer(40), "XL");map.put(new Integer(50), "L");map.put(new Integer(60), "LX");map.put(new Integer(70), "LXX");map.put(new Integer(80), "LXXX");map.put(new Integer(90), "XC");
        map.put(new Integer(100), "C");map.put(new Integer(200), "CC");map.put(new Integer(300), "CCC");map.put(new Integer(400), "CD");map.put(new Integer(500), "D");map.put(new Integer(600), "DC");map.put(new Integer(700), "DCC");map.put(new Integer(800), "DCCC");map.put(new Integer(900), "CM");
        map.put(new Integer(1000), "M");map.put(new Integer(2000), "MM");map.put(new Integer(3000), "MMM");

        StringBuffer sb = new StringBuffer();
        int temp = num / 1000;
        if(temp * 1000 != 0) sb.append(map.get(new Integer(temp * 1000)));
        temp = (num / 100) % 10;
        if(temp * 100 != 0) sb.append(map.get(new Integer(temp * 100)));
        temp = (num /10) % 10;
        if(temp * 10 != 0) sb.append(map.get(new Integer(temp * 10)));
        temp = num % 10;
        if(temp != 0) sb.append(map.get(new Integer(temp)));

        return sb.toString();
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值