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

[leetcode]Integer to Roman

时间:2014-12-04 19:59:40      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

Given an integer, convert it to a roman numeral.

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


基本思路:

熟悉罗马数字和阿拉伯数字的转换规则,并找出规律。写出程序。 此题重点在提出规律。

阿拉伯数字到罗马数字的映射可以参考http://baike.baidu.com/view/42061.htm?fr=aladdin

代码:

 string toRoman(string Roman, int size, int num)  //C++
    {
        string tmp = "";
        if(num == 0)
            return tmp;
            
        int tmpnum  = num;
        int tmpsize = size;
        while(tmpsize > 1)
        {
            tmpnum = tmpnum/10;
            tmpsize--;
        }
        int topnum = tmpnum;
        
        if(tmpnum <4)
        {
            while(tmpnum>0)
            {
                tmp += Roman.substr((size-1)*2,1);
                tmpnum--;   
            }
        }
        else if(tmpnum > 8)
        {
              tmp += Roman.substr((size-1)*2,1);
                tmp +=Roman.substr((size-1)*2+2,1);
        }
        else
        {
                if(tmpnum ==4 )
            {
              
                tmp += Roman.substr((size-1)*2,1);
                tmp += Roman.substr((size-1)*2+1,1);
                
            }
            else 
            {
                tmp += Roman.substr((size-1)*2+1,1);
                tmpnum = tmpnum-5;
                while(tmpnum>0)
                {
                    tmp += Roman.substr((size-1)*2,1);
                    tmpnum--;      
                }
                
            }
              
        }
    
        tmpsize =size;
        while(tmpsize >1)
        {
            topnum *= 10;
            tmpsize--;
        }
        
        tmp += toRoman(Roman,size-1,num-topnum);
        return tmp;
    }
    
    string intToRoman(int num) {
        string Roman = "IVXLCDM";
        int size = 0;
        int temp = num;
        while(temp >0)
        {
            size++;
            temp = temp/10;
        }
        string result = toRoman(Roman,size,num);
        return result;
    }


[leetcode]Integer to Roman

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41728715

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