标签:
1. StringIntegerToRoman
非常好的写法,重点在于1递归的使用,2用if来实现从大到小的查找,3Advance for 的使用。
package LeeCodeCrack; import java.util.*; public class StringIntegerToRoman { private static LinkedHashMap<Integer,String> numToRoman=new LinkedHashMap<Integer,String>(); static{ numToRoman.put(1000, "M"); numToRoman.put(900, "CM"); numToRoman.put(500, "D"); numToRoman.put(400, "CD"); numToRoman.put(100, "C"); numToRoman.put(90, "XC"); numToRoman.put(50, "L"); numToRoman.put(40, "XL"); numToRoman.put(10, "X"); numToRoman.put(9, "X"); numToRoman.put(5, "V"); numToRoman.put(4, "IV"); numToRoman.put(1, "I"); } //Recursion //The reason of using recuision is to ensure the function always started from the beginning //For each element public static String intToRoman(int num){ for (Integer i:numToRoman.keySet()){ //if(num>=1)ensure it always starts from the top of the list if(num>=i){ return numToRoman.get(i)+intToRoman(num-i); } } return " "; } public static void main (String[] args){ int num=2307; System.out.println(intToRoman(num)); } }
标签:
原文地址:http://www.cnblogs.com/ChrisY/p/5450096.html