当前位置: 移动技术网 > IT编程>脚本编程>Python > 罗马数字与阿拉伯数字转换

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

2019年03月24日  | 移动技术网IT编程  | 我要评论

大明审死官txt,托尼贾断骨功,汽车精品网

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

且“ii”表示2,“iii”表示3,“iv”表示4,“vi表示6”,“vii”表示7,“viii”表示8,“ix”表示9,其余的类似。

阿拉伯数转换成罗马数字

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

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

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网