LeetCode(12):整数转罗马数字

本文提供两种解决方案将整数转换为罗马数字。第一种方案通过逐位判断并使用HashMap存储罗马数字;第二种方案利用固定罗马数字进行匹配。这两种方法均能有效实现题目要求。

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

LeetCode(12):整数转罗马数字

介绍

在这里插入图片描述

题解

class Solution {
	/**
		对罗马数字也没深入研究过。理所当然的认为,需要一位一位的判断。
	**/
    public String intToRoman(int num) {
    HashMap<Integer,String>  hm = new HashMap<>();
    hm.put(1000,"M");
    hm.put(900,"CM");
    hm.put(500,"D");
    hm.put(400,"CD");
    hm.put(100,"C");
    hm.put(90,"XC");
    hm.put(50,"L");
    hm.put(40,"XL");
    hm.put(10,"X");
    hm.put(9,"IX");
    hm.put(5,"V");
    hm.put(4,"IV");
    hm.put(1,"I");
    int temp = num;
    int index = 1;
    StringBuffer sb = new StringBuffer();
    while(temp>0){
        int bit = temp%10;
        if(bit<4){
            while(bit-->0){
                sb.insert(0,hm.get(index));
            }
        }else if(bit == 4){
            sb.insert(0,hm.get(4*index));
        }else if(bit == 9){
            sb.insert(0,hm.get(9*index));
        }else{
            bit = bit -5;
            while(bit-->0){
                sb.insert(0,hm.get(index));
            }
            sb.insert(0,hm.get(5*index));
        }
        index  = index * 10;
        temp  = temp /10;
    }
    return sb.toString();
    }
}

class Solution {
	/**
		罗马数字是固定的,所以完全可以用这些固定的罗马数字来进行判断。
	**/
    public String intToRoman(int num) {   
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};    
        String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        StringBuffer s = new StringBuffer();
        for(int i =0;i<values.length;i++){
        	// 循环判断满足要求的罗马数字
            while(num>=values[i]){
                s.append(symbols[i]);
                num -= values[i];
            }
        }
        return s.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值