【Leetcode】13. Roman to Integer 罗马数字转阿拉伯数字

1. 题目

Given a roman numeral, convert it to an integer.

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

2. 思路

按序累加即可。考虑{4、9}*10^i的场景,做好减法和多跳一步。

3. 代码

耗时:29ms

class Solution {
public:
    Solution() {
        bzero(map, sizeof(map));
        map['I'] = 1;
        map['X'] = 10;
        map['C'] = 100;
        map['M'] = 1000;
        map['V'] = 5;
        map['L'] = 50;
        map['D'] = 500;
    }
    int romanToInt(string s) {
        int v = 0;
        int len = s.length();
        if (len == 0) return 0;
        if (len == 1) return map[s[0]];
        int i = 0;
        while (i < len) {
            if (s[i] == ' ') continue;
            if (i+1 < len && map[s[i+1]] > map[s[i]]) {
                v -= map[s[i]];
                v += map[s[i+1]];
                i += 2;
            } else {
                v += map[s[i]];
                i++;
            }
        }
        return v;
    }
private:
    int map[128];
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007275747
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞