LeetCode算法12:java 整数转罗马数字

版权声明:可以转载,请注明链接出处 https://blog.csdn.net/xihuanyuye/article/details/85142327

问题
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。

给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。

示例 1:
输入: 3
输出: “III”

示例 2:
输入: 4
输出: “IV”

示例 3:
输入: 9
输出: “IX”

示例 4:
输入: 58
输出: “LVIII”
解释: L = 50, V = 5, III = 3.

示例 5:
输入: 1994
输出: “MCMXCIV”
解释: M = 1000, CM = 900, XC = 90, IV = 4.

分析
很多人就这个问题进行了很复杂的逻辑算法,其实就是进行各种条件选择。但是对于规律并不太强,并且数据量有限的问题。将特定值缓存起来应该是更直观和简便的做法。因此罗马数字转换问题,这里采用Hashmap缓存法来解决。

代码

package _01_50;

import java.util.*;

public class _12IntegertoRoman{

public String intToRoman(int num){
	
			Map<Integer, String> map = new HashMap<Integer, String>();
			//HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();

			map.put(1,"I"); 
			map.put(2,"II");
			map.put(3,"III");
			map.put(4,"IV");
			map.put(5,"V");
			map.put(6,"VI");
			map.put(7,"VII");
			map.put(8,"VIII");
			map.put(9,"IX");
			
			map.put(10,"X");
			map.put(20,"XX");
			map.put(30,"XXX");
			map.put(40,"XL");
			map.put(50,"L");
			map.put(60,"LX");
			map.put(70,"LXX");
			map.put(80,"LXXX");
			map.put(90,"XC");
			
			map.put(100,"C");
			map.put(200,"CC");
			map.put(300,"CCC");
			map.put(400,"CD");
			map.put(500,"D");
			map.put(600,"DX");
			map.put(700,"DXX");
			map.put(800,"DXXX");
			map.put(900,"CM");
			
			map.put(1000,"M");
			map.put(2000,"MM");
			map.put(3000,"MMM");
	
	
		String result = "";
		
		int m = num/1000;
		int res = num%1000;
		if( m!=0){
			result = result+ map.get(m*1000);
			}
			
	  int c = res /100;
	  res = res%100;
	  if(c!=0){
	  	result = result+ map.get(c*100);
	  	}
	  int x = res/10;
	  res = res%10;
	  
	   if(x!=0){
	   	result = result+ map.get(x*10);
	   }
	   	
		int i = res;
		 if(i!=0){
	   	result = result+ map.get(i);
	   	}
		return result;
}
	public static void main(String[] arg){
		_12IntegertoRoman IntegertoRoman = new _12IntegertoRoman();
		int input1 = 1224;
		int input2 = 2224;
		int input3 = 1254;
		int input4 = 3000;
		System.out.println(IntegertoRoman.intToRoman(input1));
		System.out.println(IntegertoRoman.intToRoman(input2));
		System.out.println(IntegertoRoman.intToRoman(input3));
		System.out.println(IntegertoRoman.intToRoman(input4));
		}
}

猜你喜欢

转载自blog.csdn.net/xihuanyuye/article/details/85142327