【Leetcode】之Roman to Integer

本文介绍了一种将罗马数字转换为整数的算法实现,包括解析罗马数字字符串并计算其对应整数值的过程。

一.题目描述

Given a roman numeral, convert it to an integer.

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

二.我的解题思路

这道题跟之前的整数转罗马数字正好相反本题还更加简单些。给定一个罗马数字构成的字符串,从左向右遍历,要么是当前字符构成一个数,要么是当前字符跟之后的一个字符构成一个数,简单的加以判断即可。写好的程序如下:

class Solution {
public:
    int romanToInt(string s) {
        map<string,int> hash_map;
         const int int_sub[]={4,9,40,90,400,900,1,5,10,50,100,500,1000};
        const string sub[] ={"IV","IX","XL","XC","CD","CM","I","V","X","L","C","D","M"};
        for(int i=0;i<sizeof(int_sub)/sizeof(int);i++)
            hash_map[sub[i]]=int_sub[i];
        int i=0;
        string tmp("");
        int res=0;
        char curr='0';char next='0';
     while( i<s.length())
        {
            tmp=s[i];
            if(i<s.length()-1)
            {
                tmp=tmp+s[i+1];
                if(hash_map[tmp]>0)
                {
                    res=res+hash_map[tmp];
                    i=i+2;
                    continue;
                }

            }
         tmp=s[i];
            res=res+hash_map[tmp];
            i++;
        }
        return res;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值