首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 罗马数字转整数 多种解法

python 罗马数字转整数 多种解法

作者头像
编程小白狼
发布2024-12-31 08:12:14
发布2024-12-31 08:12:14
1600
举报
文章被收录于专栏:编程小白狼编程小白狼

解法一:使用字典映射

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-12-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档