[LeetCode] 13. Roman to Integer

题目链接:传送门

Description

Given a roman numeral, convert it to an integer.

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

Solution

题意:

把一个罗马数字转化成阿拉伯数字

思路:

主要是对罗马数字表示法的认识

Wikipedia:Roman numerals

主要是 Basic decimal pattern 这一段的描述

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> romanVal;
        romanVal['I'] = 1;
        romanVal['V'] = 5;
        romanVal['X'] = 10;
        romanVal['L'] = 50;
        romanVal['C'] = 100;
        romanVal['D'] = 500;
        romanVal['M'] = 1000;
        
        int len = s.length(), res = romanVal[s[len - 1]];
        for (int i = len - 2; i >= 0; i--) {
            if (romanVal[s[i]] < romanVal[s[i + 1]]) {
                res -= romanVal[s[i]];
            } else {
                res += romanVal[s[i]];
            }
        }
        return res;
    }
};
/*
I	V	X	L	C	D	M
1	5	10	50	100	500	1,000
*/

在Discuss中看到 unordered_map 方便的初始化...

unordered_map<char, int> T = { { 'I' , 1 },
                               { 'V' , 5 },
                               { 'X' , 10 },
                               { 'L' , 50 },
                               { 'C' , 100 },
                               { 'D' , 500 },
                               { 'M' , 1000 } };
posted @ 2018-02-14 01:46  酒晓语令  阅读(71)  评论(0编辑  收藏  举报