13. Roman to Integer

13. Roman to Integer

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

分析
罗马数字对应相应的阿拉伯数字
考虑使用hash表中的键值对
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

根据题目的描述,如果在一个罗马数字的左边有一个比它小的罗马数字,那么用大的值减去小的值,例如 IX为4.如果在一个罗马数字的右边有一个比它的罗马数字,用大的值加上小的值。例如 XI为6.

class Solution {
private:
    unordered_map<char,int> MyMap = {
        {'I', 1},
        {'V', 5},
        {'X', 10},
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000},
    };
public:
    int romanToInt(string s) {
            int sum = 0;//数字的值
            int len = s.length();
            for(int i = 0;i<len;++i){
                //获取当前罗马数字所代表的值
                 int value = MyMap[s[i]];
                //如果一个罗马数字前面有比它小的值,则用小的值减去它的值。反之则加上
                if(i<len-1 && value < MyMap[s[i+1]]){
                    sum = sum-value;
                }else{
                    sum = sum+value;
                }
            }
            return sum;
    }
};

注意
注意键值对的对应关系,int char

头文件
#include<unordered_map>

#include< map>

#include< string>

插入值,如果值已经存在,则进行赋值覆盖修改

#include <iostream>
#include<unordered_map>
#include<map>
#include<string>
using namespace std;
int main()
{
    unordered_map<int,string> myMap = {{2,"特鲁"},{3,"赵四"}};
    //插入值,如果值已经存在,则进行赋值修改。
    myMap[4] = "老爹";
    myMap[10] = "小玉";

//迭代器输出
    auto iter = myMap.begin();
    while(iter!=myMap.end()){
        cout<<iter->first<<","<<iter->second<<endl;
        ++iter;
    }
  return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值