LeetCode Integer to Roman

本文介绍了一种将整数转换为罗马数字的算法实现,适用于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

分析:

罗马数字由“IVXLCDM”等组成,分别表示1,5,10,50,100,500,1000。

根据规则个位数上的1 2 3 4 5 6 7 8 9的罗马表示为I II III IV V VI VII VIII IX

十位数上的1 2 3 4 5 6 7 8 9的罗马表示为X XX XXX XL L LX LXX LXXX XC

百位数上的1 2 3 4 5 6 7 8 9的罗马表示为C CC CCC CD D DC DCC DCCC CM

千位数上的1 2 3的罗马表示为M MM MMM

class Solution {
public:
    string intToRoman(int num) {
        char roman[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
    	string result;
    	for(int i = 0; num > 0; i += 2, num /= 10) {
    		int x = num % 10;
    		switch(x) {
    			case 1:
    			case 2:
    			case 3:
    				result = string(x, roman[i]) + result;
    				break;
    			case 4:
    				result = roman[i+1] + result;
    				result = roman[i] + result;
    				break;
    			case 5:
    				result = roman[i+1] + result;
    				break;
    			case 6:
    			case 7:
    			case 8:
    				result = string(x-5, roman[i]) + result;
    				result = roman[i+1] + result;
    				break;
    			case 9:
    				result = roman[i+2] + result;
    				result = roman[i] + result;
    				break;
    			default:
    				break;		
    		}
    	}
    	return result;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值