Integer to Roman (整数转罗马数字)

Given an integer, convert it to a roman numeral.

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

题目本身很简单 就是给一个1到3999的数字 转换成IVXLCDM这几个字母的罗马字符串。 但是 一个数字可以拆成的组合非常多,可以有很多种合理的组合,这里经过一次提交发现题目中对于4,40,400的表示应该是5-1,50-10,500-100, 对于9,99,999的表示应该是IX,XC,CM 那就直接做一个映射表好了 ,其他的数字都累加 比如1,2,3就分别是1个I,2个I,3个I ,因为他们小于5, 对于大于5的,就先输出5所对应的的V再输入一个I,两个I,三个I。

class Solution {
public:
	string intToRoman(int num) {
		// Note: The Solution object is instantiated only once and is reused by each test case. 
		string result;
		if (num == 0) return result;
		int divisor = 1000, repeat = 0;
		while (num > 0)
		{
			repeat = num / divisor;
			if (repeat == 4 || repeat == 5 || repeat == 9) 
			{
				result += mapInt(repeat * divisor);
				repeat = 0;
			}
			if (repeat > 5) 
			{
				result += mapInt(5 * divisor);
				repeat -= 5;
			}
			while (repeat)
			{
				result += mapInt(divisor);
				--repeat;
			}
			num %= divisor;
			divisor /= 10;
		}
		return result;
	}
private:
	string mapInt(int integer)
	{
		switch (integer)
		{
		case 1: return "I";
		case 4: return "IV";
		case 5: return "V";
		case 9: return "IX";
		case 10: return "X";
		case 40: return "XL";
		case 50: return "L";
		case 90: return "XC";
		case 100: return "C";
		case 400: return "CD";
		case 500: return "D";
		case 900: return "CM";
		case 1000: return "M";
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值