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

Integer to Roman

时间:2014-09-12 11:55:43      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   io   java   ar   for   div   sp   

Given an integer, convert it to a roman numeral.

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

答案

public class Solution {
    Map<Integer,Character>mapInt2Char=new HashMap<Integer,Character>();
    Map<Integer,Integer>mapLeftInt=new HashMap<Integer,Integer>();
    int currentValue[]={1000,500,100,50,10,5,1};
    int minValue[]={900,400,90,40,9,4,1};
    int maxValue[]={3999,899,399,89,39,8,3};
    {
        mapInt2Char.put( 1,'I');
        mapInt2Char.put( 5,'V');
        mapInt2Char.put( 10,'X');
        mapInt2Char.put( 50,'L');
        mapInt2Char.put( 100,'C');
        mapInt2Char.put( 500,'D');
        mapInt2Char.put( 1000,'M');
    }
    {
        mapLeftInt.put(1000, 100);
        mapLeftInt.put(500, 100);
        mapLeftInt.put(100, 10);
        mapLeftInt.put(50, 10);
        mapLeftInt.put(10, 1);
        mapLeftInt.put(5, 1);
    }
    public String intToRoman(int num) {
        String result="";
        if(num<=0)
            return result;
        for(int i=0;i<currentValue.length;i++){
            if(num>=minValue[i])
            {
                int current=currentValue[i];
                if(num==current){
                   result=""+mapInt2Char.get(current);
                }
                else if(num<current){
                    int left=mapLeftInt.get(current);
                    int dest=num+left-current;
                    result=""+mapInt2Char.get(left)+mapInt2Char.get(current);
                    if(dest>0)
                    {
                        result+=intToRoman(dest);
                    }
                }
                else
                {
                    int dest=num;
                    while(dest>current){
                        result+=""+mapInt2Char.get(current);
                        dest-=current;
                    }
                    if(dest>0)
                    {
                        result+=intToRoman(dest);
                    }
                }
                break;
            }
        }
        return result;
    }
}


Integer to Roman

标签:des   style   color   io   java   ar   for   div   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39227875

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