题注
其实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一共只有下列几个关键字:
Symbol | Value |
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
接下来说说具体的表示方法。首先,根据上面的表格,每个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;
}
}