问题
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Tags: Math, String
代码
public class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
map.put(‘I‘, 1);
map.put(‘V‘, 5);
map.put(‘X‘, 10);
map.put(‘L‘, 50);
map.put(‘C‘, 100);
map.put(‘D‘, 500);
map.put(‘M‘, 1000);
int result = 0;
int len = s.length();
for (int i = 0; i < len - 1; i++) {
char c = s.charAt(i);
int add = map.get(c);
switch (c) {//参考文章下面说明中的计算规则
case ‘I‘:
if (s.charAt(i + 1) == ‘V‘ || s.charAt(i + 1) == ‘X‘) result -= add;
else result += add;
break;
case ‘X‘:
if (s.charAt(i + 1) == ‘L‘ || s.charAt(i + 1) == ‘C‘) result -= add;
else result += add;
break;
case ‘C‘:
if (s.charAt(i + 1) == ‘D‘ || s.charAt(i + 1) == ‘M‘) result -= add;
else result += add;
break;
case ‘V‘:
case ‘L‘:
case ‘D‘:
case ‘M‘:
result += add;
break;
default:
break;
}
}
return result + map.get(s.charAt(len - 1));
}
}
运行时间
说明
罗马数字的计算规则,参考如下几点:
基本字符
(‘I’, 1) (‘V’, 5) (‘X’, 10) (‘L’, 50) (‘C’, 100) (‘D’, 500) (‘M’, 1000)
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、V 和X 左边的小数字只能用Ⅰ。
5、L 和C 左边的小数字只能用X。
6、D 和M 左边的小数字只能用C。
链接:罗马数字 百度百科
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode #13 Roman to Integer #Java
原文地址:http://blog.csdn.net/jiangwei0829/article/details/46698983