Leetcode题目之求罗马数字字符串转换为阿拉伯数字的值的结果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36470920/article/details/84963962

题目其实挺长,主要说了关于罗马数字字符对应于阿拉伯数字的知识,另外介绍了如何将一个字符串转换为数字的计算方法,见下面的描述:

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

其中要注意的是,关于6个罗马数字需要重新转换,那就是IV,IX,XC,XL,CD,CM这6个数字

刚开始真的是一筹莫展,后面看了大神的代码才恍然大悟,其实思想就是:

首先建立一个字典类型,分别是罗马数字和其对应的阿拉伯数值,一共7个,然后开始遍历输入的目标字符串,当开始第一个字符,我们把它复制给另一个字符串,然后先让num,即就是最后的结果,加上这个罗马数字对应的数值,然后遍历下一个字符,开始比较这两个字符对应的字典里面的value值的大小,当发现前者比后者大时,肯定不会是组合数字,那就不需要做任何处理,最后的结果自然而然就是各种加和。当发现前者比后者小的时候,说明是组合数值,这个时候有一个规律,即组合字符的对应的数值等于两者加起来的数值的和减去前者字符对应的数值大小的2倍。

因此结果就很容易求出来了,这道问题也就解决的差不多了。

如下是代码:

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        num = 0
        objstr = ""
        for rs in s:
            if (rs in d):
                num += d[rs]
            if (len(objstr) > 0):
                if (d[objstr] == d[rs]):
                    continue
                #'CD'==400==C(100)+D(500)-2*C(100)
                #'CM'==900==C(100)+M(1000)-2*C(100)
                #'XL'==40==X(10)+M(50)-2*X(10)
                #'XC'==90==X(10)+C(100)-2*X(10)
                #'IV'==4==I(1)+V(5)-2*I(1)
                #'IX'==9==I(1)+X(10)-2*I(1)
                else:
                    if (d[objstr] < d[rs]):
                        num -= (2 * d[objstr])
            objstr = rs
        return num
if __name__ == "__main__":
    S = Solution()
    obj = input("")
    print(S.romanToInt(obj))

下面是运行截图:

2018.12.12 2:16 am

猜你喜欢

转载自blog.csdn.net/qq_36470920/article/details/84963962
今日推荐