LeetCode算法题之int to Roman

来源:互联网 发布:centos启动图形界面 编辑:程序博客网 时间:2024/05/19 18:14

问题描述:
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/link?url=UUF_EffApqqZ3Hh2K_7f8NOYpFYIAtk8oWQMWkmN1KnO3TOeiitCwubqKI_boYSlsKOEij4zrwMT0oGN4Ev0YK

class Solution{public:    string intToRoman(int num)    {        map<int, char> Int_Roman;        Int_Roman.insert(pair<int,char>(1,'I'));        Int_Roman.insert(pair<int,char>(5,'V'));        Int_Roman.insert(pair<int,char>(10,'X'));        Int_Roman.insert(pair<int,char>(50,'L'));        Int_Roman.insert(pair<int,char>(100,'C'));        Int_Roman.insert(pair<int,char>(500,'D'));        Int_Roman.insert(pair<int,char>(1000,'M'));        string result;        if(num<0 || num >3999)            return "";        //确定个十百千位,他们相加起来正好等于num        int single = num % 10;        int ten = num % 100 - single;        int hundred = num % 1000 - num % 100;        int thousand = num - num % 100;        //确定千位        for(int j=0; j<thousand/1000; j++ )        {            result += Int_Roman[1000];        }        //确定百位        if(hundred == 900)        {            result += "CM";        }        else if(hundred == 400)        {            result += "CD";        }        else if(hundred < 400)        {            for(int j=0; j<hundred/100; j++ )            {                result += Int_Roman[100];            }        }        else        {            result += 'D';            for(int j=0; j<(hundred - 500)/100; j++ )            {                result += Int_Roman[100];            }        }        //确定十位        if(ten == 90)        {            result += "XC";        }        else if(ten == 40)        {            result += "XL";        }        else if(ten < 40)        {            for(int j=0; j<ten/10; j++ )            {                result += Int_Roman[10];            }        }        else        {            result += 'L';            for(int j=0; j<(ten - 50)/10; j++ )            {                result += Int_Roman[10];            }        }        //确定个位        if(single == 9)        {            result += "IX";        }        else if(single == 4)        {            result += "IV";        }        else if(single < 4)        {            for(int j=0; j<single/1; j++ )            {                result += Int_Roman[1];            }        }        else        {            result += 'V';            for(int j=0; j<(single - 5)/1; j++ )            {                result += Int_Roman[1];            }        }//.....................................................    return result;    }};
0 0
原创粉丝点击