【LeetCode 12】整数转罗马数字

思路

 类似于贪心的思想,最先使用的是较大的数字。

Version1
	public static String intToRoman(int num) {
		String ret = "";
		Map<Integer, String> hashTable = new HashMap<Integer, String>(); //写的时候发现并没有用...
		hashTable.put(1, "I");
		hashTable.put(5, "V");
		hashTable.put(10, "X");
		hashTable.put(50, "L");
		hashTable.put(100, "C");
		hashTable.put(500, "D");
		hashTable.put(1000, "M");
		hashTable.put(4, "IV");
		hashTable.put(9, "IX");
		hashTable.put(40, "XL");
		hashTable.put(90, "XC");
		hashTable.put(400, "CD");
		hashTable.put(900, "CM");
		// 1000
		while (num >= 1000)
		{
			ret += "M";
			num -= 1000;
		}
		
		// 900
		while (num >= 900)
		{
			ret += "CM";
			num -= 900;
		}
		// 500
		while (num >= 500)
		{
			ret += "D";
			num -= 500;
		}
		// 400
		while (num >= 400)
		{
			ret += "CD";
			num -= 400;
		}
		// 100
		while (num >= 100)
		{
			ret += "C";
			num -= 100;
		}
		
		// 90
		while (num >= 90)
		{
			ret += "XC";
			num -= 90;
		}
		// 50
		while (num >= 50)
		{
			ret += "L";
			num -= 50;
		}
		// 40
		while (num >= 40)
		{
			ret += "XL";
			num -= 40;
		}
		// 10
		while (num >= 10)
		{
			ret += "X";
			num -= 10;
		}
		
		// 9
		while (num >= 9)
		{
			ret += "IX";
			num -= 9;
		}
		// 5
		while (num >= 5)
		{
			ret += "V";
			num -= 5;
		}
		// 4
		while (num >= 4)
		{
			ret += "IV";
			num -= 4;
		}
		// 1
		while (num >= 1)
		{
			ret += "I";
			num -= 1;
		}
		return ret;
    }
Version2(思路和Version1相同,数组简洁版本)
	public static String intToRoman2(int num) {
		String ret = "";
		int[] n = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
		String[] m = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
		for (int i = 0; i < n.length; i++)
		{
			while (num >= n[i])
			{
				ret += m[i];
				num -= n[i];
			}
		}
		return ret;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值