GEEK编程练习— —罗马数字问题

题目

输入的是一个整数或罗马数字,若为整数,输出对应的罗马数字;若为罗马数字,输出对应的整数。数值范围从1到3999。

输入

1100

输出

MC

输入

MC

输出

1100

分析

因为输入只有两种情况,判断一下首个字符为整数还是罗马数字,分两种情况进行转换。

代码

#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>

using namespace std;

int R2IMap(const char c)
{
    switch (c)
    {
    case 'I':
        return 1;
    case 'V':
        return 5;
    case 'X':
        return 10;
    case 'L':
        return 50;
    case 'C':
        return 100;
    case 'D':
        return 500;
    case 'M':
        return 1000;
    default:
        return 0;
    }
}
int main()
{
    string str;
    cin >> str;

    if (isdigit(str[0]))
    {
        int num = atoi(str.c_str());
        const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        string roman;
        for (int i = 0; num > 0; ++i)
        {
            int ncount = num / radix[i];
            num %= radix[i];
            for (; ncount > 0; --ncount)
            {
                roman += symbol[i];
            }

        }
        cout << roman << endl;
    }
    else
    {
        int result = 0;
        for (int i = 0; i < str.size(); ++i)
        {
            if (i > 0 && R2IMap(str[i]) > R2IMap(str[i - 1]))
            {
                result += (R2IMap(str[i]) - 2 * R2IMap(str[i - 1]));
            }
            else
            {
                result += R2IMap(str[i]);
            }
        }
        cout << result << endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值