20-Integer to Roman-Leetcode

本文介绍了一种将整数转换为罗马数字的算法实现。通过使用四个映射表分别对应千位、百位、十位和个位的转换规则,并采用从低位到高位逐位转换的方法,实现了1到3999范围内整数的有效转换。

比较简单的思路:用map存放各个位的数字到罗马字符的映射
然后从个位依次遍历高位加上映射即可。
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
罗马表示法参看上一篇博文

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#define IMIN numeric_limits<int>::min()
#define IMAX numeric_limits<int>::max()
#define FR(i,n) for(int i=0;i<n;i++)
#define CLC(x) memset(x,0,sizeof(x))
#define FILL(x,c) memset(x,c,sizeof(x))
using namespace std;
class Solution {
public:
    string intToRoman(int num) {
        map<int,string> mp1,mp2,mp3,mp4;
        init1(mp1);init2(mp2);init3(mp3);init4(mp4);
        string s;
        int n=1;
        while(num)
        {
            int tmp=num%10;
            switch(n)
            {
                case 1:s=mp1[tmp]+s;break;
                case 2:s=mp2[tmp]+s;break;
                case 3:s=mp3[tmp]+s;break;
                case 4:s=mp4[tmp]+s;break;  
            }
        //  cout<<s<<endl;
        //  cout<<num<<endl;
            num = num/10;
            n++;
        }
        return s;
    }
    void init1(map<int,string> &mp)
    {
        mp[0]="";
        mp[1]=string("I");mp[2]=string("II");
        mp[3]=string("III");mp[4]=string("IV");
        mp[5]=string("V");mp[6]=string("VI");
        mp[7]=string("VII");mp[8]=string("VIII");
        mp[9]=string("IX");     
    }
    void init2(map<int,string> &mp)
    {
        mp[0]="";
        mp[1]=string("X");mp[2]=string("XX");
        mp[3]=string("XXX");mp[4]=string("XL");
        mp[5]=string("L");mp[6]=string("LX");
        mp[7]=string("LXX");mp[8]=string("LXXX");
        mp[9]=string("XC");     
    }
    void init3(map<int,string> &mp)
    {
        mp[0]="";
        mp[1]=string("C");mp[2]=string("CC");
        mp[3]=string("CCC");mp[4]=string("CD");
        mp[5]=string("D");mp[6]=string("DC");
        mp[7]=string("DCC");mp[8]=string("DCCC");
        mp[9]=string("CM");     
    }
    void init4(map<int,string> &mp)
    {
        mp[1]=string("M");mp[2]=string("MM");
        mp[3]=string("MMM");
    }
};
int main()
{
    Solution s;
    int n;
    while(cin>>n)
    cout<<s.intToRoman(n)<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/freeopen/p/5482979.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值