zoukankan      html  css  js  c++  java
  • 160-13. 罗马数字转整数

    给定一个罗马数字,转为整数(都是我写的,我很开心,如果我不思考这个问题看起来很难,但是当我思考了他就变得不是那么难)
    class Solution(object):
        data_dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    
        def get_value(self, symbol):
            """-1表示出问题了"""
            return self.data_dict.get(symbol, -1)
    
        def romanToInt1(self, s):
            """
            :type s: str
            :rtype: int
            """
            if len(s) < 2:
                return self.get_value(s) if self.get_value(s) != -1 else 0
    
            i = 0
            count = 0
            while i < len(s):
                cur_value = self.get_value(s[i])
                next_value = self.get_value(s[i + 1])
                if cur_value == -1:
                    return count
    
                if cur_value >= next_value:
                    count += cur_value
                    i += 1
                else:
                    count += next_value - cur_value
                    i += 2
    
                if i + 1 == len(s):
                    count += self.get_value(s[i])
                    break
    
            return count
    
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            i = 0
            count = 0
            while i < len(s):
                if i < len(s) - 1:
                    cur_value = self.get_value(s[i])
                    next_value = self.get_value(s[i + 1])
                    if cur_value == -1:
                        return count
    
                    if cur_value >= next_value:
                        count += cur_value
                    else:
                        count -= cur_value
                else:
                    count += self.get_value(s[i])
                i += 1
            return count
    
    
    if __name__ == '__main__':
        s1 = Solution()
        s = "D"
        print(s1.romanToInt(s))
    
  • 相关阅读:
    perlsplice
    perl中数组函数:delete和grep
    Python字符串格式化
    blast命令解释
    通俗解释托管与非托管
    四、GO语言的转义字符
    六、GO语言的指针
    五、GO语言的变量及数据类型
    一、GO语言的特点
    前台生成验证码案例
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14338323.html
Copyright © 2011-2022 走看看