开始本周的刷题~
**题目要求:**Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
拼写规则:要想了解如何解决这个问题,我们第一步肯定要了解罗马数字的编码规则,这里有一条关于编码规则的超链,拿去不谢。但是为了读者方便,这里给出一个关于罗马字母与阿拉伯数字对应的表格。
字母 | M | D | C | L | X | V | I |
---|---|---|---|---|---|---|---|
代表数字 | 1000 | 500 | 100 | 50 | 10 | 5 | 1 |
设计思路:其实这个题不是很难,解法也有很多,但是这里我想介绍的是我认为相对有点意思的解法。本着左加右减的设计规则,我们对罗马数字转换为阿拉伯数字的时候也要比较相邻两个数字的大小。
遍历顺序从前往后,所以对于第一个符号来说,我们直接读取它代表的数字就可以了。如果当前符号代表的数字比它前一个符号代表的数字小或者相等,例如:VII,初始化为5,第一轮循环I是比V小的,所以我们需要加上该数,也就是5+1 = 6,第二轮I = I,同样6+1 = 7;反之,当前符号代表的数字比它之前的一个符号代表的数字大,我们需要减去前一个数的两倍然后加上该数,例如:XIV,初始化为10,第一轮循环I
public class RomantoInteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(romanToInteger("DCXXI"));
}
public static int romanToInteger(String s){
int i, total, pre, cur;
total = charToInt(s.charAt(0));
for (i = 1; i < s.length(); i++) {
pre = charToInt(s.charAt(i - 1));
cur = charToInt(s.charAt(i));
if (cur <= pre) {
total += cur;
} else {
total = total - pre * 2 + cur;
}
}
return total;
}
public static int charToInt(char c) {
int currentResult = 0;
switch (c) {
case 'I':
currentResult = 1;
break;
case 'V':
currentResult = 5;
break;
case 'X':
currentResult = 10;
break;
case 'L':
currentResult = 50;
break;
case 'C':
currentResult = 100;
break;
case 'D':
currentResult = 500;
break;
case 'M':
currentResult = 1000;
break;
}
return currentResult;
}
}