字符串-简单13. 罗马数字转整数

本文介绍如何将罗马数字转换为整数。主要思路是使用映射存储罗马数字与对应数值,并处理特殊情况。
摘要由CSDN通过智能技术生成
  1. 罗马数字转整数
    在这里插入图片描述
    上来之后肯定是用map来存了,特殊情况2种方式考虑:
    1.一共就6种 放到map里
class Solution {
public:
    string chartoString(char x) {
        string s = "";
        s.push_back(x);
        return s;
    }
    int romanToInt(string s) {
        map<string, int> RomanMap;
        RomanMap["I"] = 1;
        RomanMap["IV"] = 4;
        RomanMap["V"] = 5;
        RomanMap["IX"] = 9;
        RomanMap["X"] = 10;
        RomanMap["XL"] = 40;
        RomanMap["L"] = 50;
        RomanMap["XC"] = 90;
        RomanMap["C"] = 100;
        RomanMap["CD"] = 400;
        RomanMap["D"] = 500;
        RomanMap["CM"] = 900;
        RomanMap["M"] = 1000;
        int IntResult = 0;
        int flag = 0;
        for(int i = s.size() - 1; i > 0 ; --i) {
            if(RomanMap.find(chartoString(s[i - 1]) + chartoString(s[i])) != RomanMap.end()) {
                cout << chartoString(s[i - 1]) + chartoString(s[i]);
                IntResult = IntResult + RomanMap[(chartoString(s[i - 1]) + chartoString(s[i]))];
                cout << IntResult << endl;
                --i;
            } else {
                IntResult = IntResult + RomanMap[chartoString(s[i])];
            }
        }
        if(RomanMap[chartoString(s[0])] >= RomanMap[chartoString(s[1])] || s.size() == 1)        
        IntResult = IntResult + RomanMap[chartoString(s[0])];  
        return IntResult;
    }
};

2.把逻辑写一下

class Solution {
public:
    int romanToInt(string s) {
        map<char, int> RomanMap;
        RomanMap['I'] = 1;
        RomanMap['V'] = 5;
        RomanMap['X'] = 10;
        RomanMap['L'] = 50;
        RomanMap['C'] = 100;
        RomanMap['D'] = 500;
        RomanMap['M'] = 1000;
        int IntResult = 0;
        int flag = 0;
        for(int i = s.size() - 1; i > 0 ; --i) {
            if(flag == 0) {
                IntResult = IntResult + RomanMap[s[i]]; 
                std::cout << "IntResult: +" << RomanMap[s[i]] << endl;
            } else {
                IntResult = IntResult - RomanMap[s[i]];
                std::cout << "IntResult: -" << RomanMap[s[i]] << endl;
            }
            if(RomanMap[s[i]] <= RomanMap[s[i - 1]]) {
                flag = 0;
            } else {
                flag = 1;
            }
        }            
        if(flag == 0) {
                IntResult = IntResult + RomanMap[s[0]]; 
                std::cout << "IntResult: +" << RomanMap[s[0]] << endl;
        } else {
                IntResult = IntResult - RomanMap[s[0]];
                std::cout << "IntResult: -" << RomanMap[s[0]] << endl;
        }
        return IntResult;
    }
};

感觉应该没什么其他思路了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值