leetcode第13题——*Roman to Integer

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

Given a roman numeral, convert it to an integer.

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

思路

这道题是12题逆向思维,事实上比12题要简单一点。我们知道:罗马数字由五个字母组合而成,分别是I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000),当有连续的低级别和高级别的字母出现时,要减去低级别字母对应的数,比如IV代表-1+5=4,IX代表-1+10=9,XL代表-10+50=40......但是当高级别和低级别连续出现则不用,比如VI就代表5+1=6,LXXX代表50+10+10+10=80. 
比如:1-12的罗马数字分别为Ⅰ、Ⅱ、Ⅲ、Ⅳ(IIII)、Ⅴ、Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ、Ⅺ、Ⅻ
知道以上规律后,解题就很简单了。输入一个罗马数字字符串,遍历该字符串,遍历到某字母就将结果加上这个字母对应的数字(结合后面位置的字母,也可能是加上一个负数)。注意用switch/case语句可以使得代码更简洁,并缩短运行时间。

代码

Python
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        sLen = len(s)
        res = 0
        for i in range(0,sLen):
            if s[i] == 'M':
                res += 1000
            if s[i] == 'D':
                res += 500
            if s[i] == 'C':
                if (i < sLen - 1) and (s[i+1] == 'D' or s[i+1] == 'M'):
                    res -= 100
                else:
                    res += 100
            if s[i] == 'L':
                res += 50
            if s[i] == 'X':
                if (i < sLen - 1) and (s[i+1] == 'L' or s[i+1] == 'C'):
                    res -= 10
                else:
                    res += 10
            if s[i] == 'V':
                res += 5
            if s[i] == 'I':
                if (i < sLen - 1) and (s[i+1] == 'V' or s[i+1] == 'X'):
                    res -= 1
                else:
                    res += 1
        return res
Java
public class Solution {
    public int romanToInt(String s) {
        int sLen = s.length();
		int res = 0;
		for(int i = 0;i < sLen;i++){
			switch(s.charAt(i)){
			case 'M':res += 1000;break;
			case 'D':res += 500;break;
			case 'C':{
				if ((i < sLen - 1) && (s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M')) res -= 100;
				else res += 100;
				break;
			}
			case 'L':res += 50;break;
			case 'X':{
				if ((i < sLen - 1) && (s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C')) res -= 10;
                else res += 10;
                break;
			}
			case 'V':res += 5;break;
			case 'I':{
				if ((i < sLen - 1) && (s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X')) res -= 1;
                else res += 1;
                break;
			}
			}
		}
		return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值