前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >罗马数字与阿拉伯数字转换

罗马数字与阿拉伯数字转换

作者头像
py3study
发布2020-01-17 16:12:43
8340
发布2020-01-17 16:12:43
举报
文章被收录于专栏:python3

罗马数字与阿拉伯数字对应关系如下:

且“II”表示2,“III”表示3,“IV”表示4,“VI表示6”,“VII”表示7,“VIII”表示8,“IX”表示9,其余的类似。

阿拉伯数转换成罗马数字

代码语言:javascript
复制
class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        
        if not num:
            return ""
        out = ""
        i = 3
        while i >= 0:
            out += self.get_roman(i,num//(10**i))
            num %= (10**i)
            i -= 1      
        return out
    
    def get_roman(self,power,quotient):
        power_to_roman = {0:["I","V","X"],1:["X","L","C"],2:["C","D","M"],3:["M"]}
        romans = power_to_roman[power]
        if quotient <= 3:
            out = quotient*romans[0]
        elif quotient == 4:
            out = romans[0]+romans[1]
        elif quotient == 5:
            out = romans[1]
        elif quotient <= 8:
            out = romans[1]+(quotient-5)*romans[0]
        else:
            out = romans[0]+romans[2]
        return out

罗马数字转换为阿拉伯数字:

代码语言:javascript
复制
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        Roman_to_num = {'I':1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        before = {"V":"I","X":"I","L":"X","C":"X","D":"C","M":"C"}
        
        stack = []
        num = 0
        i = len(s)-1
        while i >= 0:
            if not stack:
                stack.append(s[i])
            else:
                last = stack.pop()
                if last in before and s[i] == before[last]:
                    num += Roman_to_num[last] - Roman_to_num[s[i]]
                else:
                    stack.append(last)
                    stack.append(s[i])
            i -= 1
        for i in stack:
            num += Roman_to_num[i]
        return num
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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