leetcode题解 || Roman to Integer问题

Posted wgwyanfs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode题解 || Roman to Integer问题相关的知识,希望对你有一定的参考价值。

problem:

Given a roman numeral, convert it to an integer.

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

将罗马数字转为整数


thinking:

(1)罗马数字规则:

罗马数字共同拥有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。

依照下述的规则能够表示随意正整数。

须要注意的是罗马数字中没有“0”,与进位制无关。一般认為罗马数字仅仅用来记数,而不作演算。


反复数次:一个罗马数字反复几次,就表示这个数的几倍。
右加左减:
在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
左减的数字有限制。仅限于I、X、C。比方45不能够写成VL。仅仅能是XLV
可是,左减时不可跨越一个位数。比方。99不能够用IC(100 - 1)表示,而是用XCIX([100 - 10] + [10 - 1])表示。(等同於阿拉伯数字每位数字分别表示。)
左减数字必须為一位,比方8写成VIII,而非IIX。
右加数字不可连续超过三位,比方14写成XIV,而非XIIII。(见下方“数码限制”一项。


加线乘千:
在罗马数字的上方加上一条横线或者加上下标的?,表示将这个数乘以1000。即是原数的1000倍。
同理,假设上方有两条横线,即是原数的1000000(1000^{2})倍。
数码限制:
同一数码最多仅仅能出现三次,如40不可表示為XXXX,而要表示為XL。
例外:由於IV是古罗马神话主神朱庇特(即IVPITER,古罗马字母裡没有J和U)的首字,因此有时用IIII取代Ⅳ。

code:

class Solution {
public:
    int romanToInt(string s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int result=0;
        
        map<char,int> roman;
        roman[‘I‘]=1;
        roman[‘V‘]=5;
        roman[‘X‘]=10;
        roman[‘L‘]=50;
        roman[‘C‘]=100;
        roman[‘D‘]=500;
        roman[‘M‘]=1000;
        
        for(int i=s.length()-1;i>=0;i--)
        {
            if(i==s.length()-1)
            {
                result=roman[s[i]];
                continue;
            }
            if(roman[s[i]] >= roman[s[i+1]])
                result+=roman[s[i]];
            else
                result-=roman[s[i]];
        }
        return result;
    }
};





















以上是关于leetcode题解 || Roman to Integer问题的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode013. Roman to Integer

LeetCode:Roman to Integer

Leetcode:Integer To Roman(C语言版)

Leetcode:Integer To Roman(C语言版)

leetcode 136:roman-to-integer&&leetcode 137:integer-to-roman

LeetCode: Roman to Integer