LeetCode - Roman to Integer

题注

其实LeetCode AC Rate中间的一些题我前几天就做了,主要因为大年初五和初六和朋友们一起出去玩肯定没法做嘛,因此提前就做了。不过本着尽可能每天1-3道题的速度,做完一天的题再补前面的确实有点累… 以后慢慢补上,希望最后能做一个答案的大汇总,不求最精练,但求考虑尽可能所有的问题吧!今天这最后一道题还挺有意思,补充了Roman Number表示方法的知识,也算是更有收获了。

题目

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

分析

首先来说说为什么输入的范围为1到3999。实际上,根据Wikipedia的介绍[1],Roman numerals一共只有下列几个关键字:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000
由于没有5000的表示方法,因此Roman numeral用这种方法表示的话最高只能到3999。

接下来说说具体的表示方法。首先,根据上面的表格,每个Symbol代表对应的Value。然而,带4和带9的数需要特殊的表示:

对于4,不写为IIII,而是写为IV,表示4 = 5 - 1;

对于9,写为IX,表示9 = 10 - 1;

同理,40写为XL,90写为XC;400写为CD;900写为CM;

因此,在代码中只需要讨论上面的几种特殊情况,剩下的输入字符是多少就把结果加上多少就好了。另外还要注意的是,判断特殊情况的时候,要考虑IndexOutofBound的问题。举例来说,看到I,需要判断后面跟的是不是V或者X,但是,如果只是一个I,那么再检索后面的时候范围就溢出了。因此要增加一个判断。其他就没什么需要注意的了。

代码

public class Solution {
    public int romanToInt(String s) {
        if (s == null){
        	return 0;
        }
        int result = 0;
        int maxLength = s.length();
        int i = 0;
        while (i < maxLength){
        	switch(s.charAt(i)){
        	case 'M':
        		result += 1000;
        		i++;
        		break;
        	case 'D':
        		result += 500;
        		i++;
        		break;
        	case 'C':
        		if (i + 1 < maxLength && s.charAt(i+1) == 'D'){
        			result += 400;
        			i += 2;
        		}else if (i + 1 < maxLength && s.charAt(i+1) == 'M'){
        			result += 900;
        			i += 2;
        		}else {
        			result += 100;
        			i++;
        		}
        		break;
        	case 'L':
        		result += 50;
        		i++;
        		break;
        	case 'X':
        		if (i + 1 < maxLength && s.charAt(i+1) == 'L'){
        			result += 40;
        			i += 2;
        		}else if (i + 1 < maxLength && s.charAt(i+1) == 'C'){
        			result += 90;
        			i += 2;
        		}else{
        			result += 10;
        			i++;
        		}
        		break;
        	case 'V':
        		result += 5;
        		i++;
        		break;
        	case 'I':
        		if (i + 1 < maxLength && s.charAt(i+1) == 'V'){
        			result += 4;
        			i += 2;
        		}else if (i + 1 < maxLength && s.charAt(i+1) == 'X'){
        			result += 9;
        			i += 2;
        		}else{
        			result += 1;
        			i++;
        		}
        		break;
        	default:
        		break;
        	}
        }
        return result;  	
    }
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值