码迷,mamicode.com
首页 > 其他好文 > 详细

第四天

时间:2016-05-01 10:59:02      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!