13、Roman to Integer

来源:互联网 发布:linux漏洞公布 编辑:程序博客网 时间:2024/05/16 06:37

题目:

Given a roman numeral, convert it to an integer.

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

解题思路:

c++版本:

class Solution {public:    int toNum(char c)    {        switch(c)        {            case 'I':return 1;            case 'V':return 5;            case 'X':return 10;            case 'L':return 50;            case 'C':return 100;            case 'D':return 500;            case 'M':return 1000;        }    }    int romanToInt(string s) {        int res = toNum(s[0]);        for(int i=1;i<s.length();i++)        {            if(toNum(s[i-1])<toNum(s[i]))                res += toNum(s[i])-2*toNum(s[i-1]);            else                res += toNum(s[i]);        }        return res;    }};
python 版本:

class Solution(object):    def romanToInt(self, s):        """        :type s: str        :rtype: int        """        def toNum(c):            if c=='I':return 1;            if c=='V':return 5            if c=='X':return 10            if c=='L':return 50            if c=='C':return 100            if c=='D':return 500            if c=='M':return 1000        res = 0        if(len(s)>0):res = toNum(s[0])        for i in range(1,len(s)):            if toNum(s[i-1])<toNum(s[i]):                res += toNum(s[i])-2*toNum(s[i-1])            else:                res += toNum(s[i])        return res        



0 0
原创粉丝点击