LeetCode : No13 Roman to Integer

题目:

https://leetcode.com/problems/roman-to-integer/

 

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

规则神马的忽略···

耗时:170ms

class Solution:
    # @param {string} s
    # @return {integer}
    def romanToInt(self, s):
        i = 0
        Int = 0
        Len = len(s)
        while (i < Len):
            #
            while (i<Len and s[i]=='M'):
                Int += 1000
                i += 1

            if (i<Len and s[i]=='D'):
                Int += 500
                i += 1
                while (i<Len and s[i]=='C'):
                    Int += 100
                    i += 1
            elif (s[i:i+2] == 'CM'):
                Int += 900
                i += 2
            elif (s[i:i+2] == 'CD'):
                Int += 400
                i += 2
            else:
                while (i<Len and s[i]=='C'):
                    Int += 100
                    i += 1

            if (i<Len and s[i]=='L'):
                Int += 50
                i += 1
                while (i<Len and s[i]=='X'):
                    Int += 10
                    i += 1
            elif (s[i:i+2] == 'XC'):
                Int += 90
                i += 2
            elif (s[i:i+2] == 'XL'):
                Int += 40
                i += 2
            else:
                while (i<Len and s[i]=='X'):
                    Int += 10
                    i += 1

            if (i<Len and s[i]=='V'):
                Int += 5
                i += 1
                while (i<Len and s[i]=='I'):
                    Int += 1
                    i += 1
            elif (s[i:i+2] == 'IX'):
                Int += 9
                i += 2
            elif (s[i:i+2] == 'IV'):
                Int += 4
                i += 2
            else:
                while (i<Len and s[i]=='I'):
                    Int += 1
                    i += 1
                
        return Int


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值