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))
    
  • 相关阅读:
    C#操作Redis Set 无序集合
    C#操作Redis Hash数据表
    C#操作Redis List 列表
    C#操作Redis String字符串
    Redis 小结
    建造者模式
    外观模式
    模板方法模式
    原型模式
    select ie6 的bug 层级
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14338323.html
Copyright © 2011-2022 走看看