python 罗马数字转整数 多种解法
  2w4aEVgWpeJp 2023年12月22日 25 0

解法一:使用字典映射

def roman_to_int(s):
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    result = 0
    prev_value = 0
    for c in s[::-1]:
        current_value = roman_dict[c]
        if current_value >= prev_value:
            result += current_value
        else:
            result -= current_value
        prev_value = current_value
    return result

解法二:使用列表和条件判断

def roman_to_int(s):
    roman_list = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
    roman_value = [1, 5, 10, 50, 100, 500, 1000]
    result = 0
    prev_value = 0
    for c in s[::-1]:
        current_value = roman_value[roman_list.index(c)]
        if current_value >= prev_value:
            result += current_value
        else:
            result -= current_value
        prev_value = current_value
    return result

解法三:使用正则表达式替换

import re

def roman_to_int(s):
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    pattern = re.compile('(IV|IX|XL|XC|CD|CM)')
    s = pattern.sub(lambda x: str(roman_dict[x.group(0)[1]]) + str(roman_dict[x.group(0)[0]]), s)
    result = sum([roman_dict[c] for c in s])
    return result

解法四:使用循环和条件判断

def roman_to_int(s):
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    result = 0
    i = len(s) - 1
    while i >= 0:
        if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
            result += roman_dict[s[i]] - roman_dict[s[i-1]]
            i -= 2
        else:
            result += roman_dict[s[i]]
            i -= 1
    return result

解法五:使用字典映射和循环

def roman_to_int(s):
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    result = 0
    for i in range(len(s)):
        if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
            result += roman_dict[s[i]] - 2 * roman_dict[s[i-1]]
        else:
            result += roman_dict[s[i]]
    return result
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月22日 0

暂无评论

推荐阅读
2w4aEVgWpeJp