Leetcode刷题笔记42-罗马数字转整数

1. 题目

罗马数字包含以下七种字符:I, V, X, LCD 和 M

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

  • I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
  • X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
  • C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。

给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

示例 1:

输入: "LVIII"
输出: 58
解释: C = 100, L = 50, XXX = 30, III = 3.

示例 2:

输入: "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.

2. 解答

python3

思路:不知道为什么,用了一个特别蠢的实现方式。

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        for i in range(len(s)):
            if s[i] == 'M':
                if i != 0 and s[i-1] == 'C':
                    continue
                else: res += 1000
            elif s[i] == 'D':
                if i != 0 and s[i-1] == 'C':
                    continue
                else: res += 500
            elif s[i] == 'C':
                if i != len(s)-1 and s[i+1] == 'D':
                    res += 400
                elif i != len(s)-1 and s[i+1] == 'M':
                    res += 900
                elif i != 0 and s[i-1] == 'X':
                    continue
                else: res += 100
            elif s[i] == 'L':
                if i != 0 and s[i-1] == 'X':
                    continue
                else: res += 50
            elif s[i] == 'X':
                if i != 0 and s[i-1] == 'I':
                    continue
                elif i != len(s)-1 and s[i+1] == 'L':
                    res += 40
                elif i != len(s)-1 and s[i+1] == 'C':
                    res += 90
                else: res += 10
            elif s[i] == 'V':
                if i != 0 and s[i-1] == "I":
                    continue
                else: res += 5
            elif s[i] == 'I':
                if i != len(s)-1 and s[i+1] == 'V':
                    res += 4
                elif i != len(s)-1 and s[i+1] == 'X':
                    res += 9
                else: res += 1
        return res
# rom = "LVIII"
rom = "MCMXCIV"
s = Solution().romanToInt(rom)
print(s)

3. 优答

python3

出现特例的前提:罗马数字中大的数字在小的数字的右边。

class Solution:
    def romanToInt(self, s):
        numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100, "D": 500, "M": 1000}
        decimal = 0
        for i in range(len(s)):
            if i > 0 and numeral_map[s[i]] > numeral_map[s[i - 1]]:
                decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]
            else:
                decimal += numeral_map[s[i]]
        return decimal
# rom = "LVIII"
rom = "MCMXCIV"
s = Solution().romanToInt(rom)
print(s)

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9193573.html
今日推荐