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

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

题目原型:

Given an integer, convert it to a roman numeral.

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

基本思路:

题目的意思是给你你一个整数然后把这个整数转为罗马数字形式。例如:1899->MDCCCXCIX,注意:I表示1,V表示5,X表示10,L表示50,C表示100,D表示500,M表示1000.题目比较简单:

	public String intToRoman(int num)
	{
		StringBuffer strbuf = new StringBuffer();
		Map<Integer,String> map = new HashMap<Integer,String>();
		map.put(1 , "I");
		map.put(5 , "V");
		map.put(10 , "X");
		map.put(50 , "L");
		map.put(100 , "C");
		map.put(500 , "D");
		map.put(1000 , "M");
		
		while(num>0)
		{
			//求得第一個數字
			String numStr = new Integer(num).toString();
			int firstNum =	numStr.charAt(0)-'0';
			int elseNum = 0;//去除第一个数后的余数
			int lenOfelseNum = numStr.length()-1;//余数的长度
			if(num>=10)
				elseNum = Integer.parseInt(numStr.substring(1));
			int times = (int)Math.pow(10, lenOfelseNum);//倍数
			if(map.containsKey(firstNum*times))
			{
				strbuf.append(map.get(firstNum*times));
			}
			else if(firstNum<4)
			{
				while(firstNum>0)
				{
					strbuf.append(map.get(1*times));
					firstNum--;
				}
			}
			else if(firstNum==4||firstNum==9)
				strbuf.append(map.get(1*times)).append(map.get((firstNum+1)*times));
			else if(firstNum>5&&firstNum<9)
			{
				strbuf.append(map.get(5*times));
				firstNum-=5;
				while(firstNum>0)
				{
					strbuf.append(map.get(1*times));
					firstNum--;
				}
			}
			
			num = elseNum;
		}
		return strbuf.toString();
	}