Leetcode - 13罗马数字转整数

13 罗马数字转整数

题目描述

Leetcode - 13罗马数字转整数_第1张图片
Leetcode - 13罗马数字转整数_第2张图片

题目分析

无非是注意如果小数出现在大数前面,要减掉小数即可。

代码如下:

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

Leetcode - 13罗马数字转整数_第3张图片

2、数组
class Solution {
public:
    int romanToInt(string s) {
        int a[26] = {0};
        a['I'-'A'] = 1;
        a['V'-'A'] = 5;
        a['X'-'A'] = 10;
        a['L'-'A'] = 50;
        a['C'-'A'] = 100;
        a['D'-'A'] = 500;
        a['M'-'A'] = 1000;
        int res = 0;
        int max = 1;
        for (int i = s.size() - 1; i >= 0; i--){
            if (a[s[i]-'A'] >= max){
                max = a[s[i]-'A'];
                res += a[s[i]-'A'];
            }
            else res -= a[s[i]-'A'];
        }
        return res;
    }
};

Leetcode - 13罗马数字转整数_第4张图片

你可能感兴趣的:(Leetcode)