【Leetcode/Python】013-roman-to-integer

Question

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. 
X can be placed before L (50) and C (100) to make 40 and 90. 
C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

总的原则,如果当前循环数比后一位数小,则减去当前数;如果大则累加。

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dict = {"I":1, "V": 5, "X":10,"L":50,"C":100, "D":500, "M":1000}
        num = 0
        for i in range(len(s)-1):
            head = s[i]
            p = s[i+1]
            if dict[head] < dict[p]:
                num -= dict[head]
            else:
                num += dict[head]
        
        num += dict[s[-1]]
        
        return num
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,954评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,569评论 0 23
  • 但凡见过我搬东西的人,都会认为我是一个女汉子,然后惊讶于我的体型表现。 暑假在一家工厂干活,有一些搬搬东西的话,不...
    DreamingW阅读 875评论 3 3
  • Lithromantic
    北北爱唱歌阅读 109评论 0 0
  • 19世纪中叶,弗洛伦斯发现切除动物一部分皮层导致的行为损伤,经过一段时间能康复到接近正常的情况,动物行为损伤的程度...
    老蜗的壳阅读 1,090评论 0 0

友情链接更多精彩内容