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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int result = 0;
        for(int i = 0; i<s.size();i++)
        {
            result += getNum(s[i]);
        }
        
        int pre = 0;
        int cur = getNum(s[0]);
        
        for(int i = 1; i<s.size();i++)
        {
            pre = cur;
            cur = getNum(s[i]);
            if((pre * 5 == cur) || (pre * 10 == cur))
            {
                result -= 2*pre;
            }
        }
        
        return result;
    }
    
    int getNum(char c)
    {
        switch(c)
        {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11704531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞