Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
其实这两道题只是把输入输出反过来而已。不过在写代码之前,还是了解了Roman数字的表示方法。
基本字符 I V X L C D M
相应的阿拉伯数字表示为 1 5 10 50 100 500 1000
有几条须注意掌握:
-
基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
-
不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
-
V 和X 左边的小数字只能用Ⅰ。
-
L 和C 左边的小数字只能用X。
-
D 和M 左边的小数字只能用C。
Integer to Roman:关键在于900-1000,400-500,90-100,40-50,9,4.由于基本数字不超过3个导致了这些数字的特殊性,要把某些小的数字放在大数字左边,这样的结果是相减的结果。
Roman to Integer:HashMap把roman作为关键字,把其代表值作为value。关键在于如果判断有一些减法情况。在这样其实选择了最简单的,i+1的value大于i的value的话,得到的值为get(s(i+1))-get(s(i));并把i向后移动2个。
public class Solution {
public int romanToInt(String s) {
HashMap<Character,Integer> roman = new HashMap<Character,Integer>();
roman.put('I', 1);
roman.put('V', 5);
roman.put('X',10);
roman.put('L',50);
roman.put('C',100);
roman.put('D',500);
roman.put('M',1000);
char[] ch = s.toCharArray();
int length = ch.length;
int i=0;
int result = 0;
while(i<length)
{
if((i<length-1)&&roman.get(ch[i])<roman.get(ch[i+1]))
{
result = result + roman.get(ch[i+1]) - roman.get(ch[i]);
i = i + 2;
}
else
{
result = result + roman.get(ch[i]);
i = i + 1;
}
}
return result;
}
}
public class Solution {
public int romanToInt(String s) {
HashMap<Character,Integer> roman = new HashMap<Character,Integer>();
roman.put('I', 1);
roman.put('V', 5);
roman.put('X',10);
roman.put('L',50);
roman.put('C',100);
roman.put('D',500);
roman.put('M',1000);
char[] ch = s.toCharArray();
int length = ch.length;
int i=0;
int result = 0;
while(i<length)
{
if((i<length-1)&&roman.get(ch[i])<roman.get(ch[i+1]))
{
result = result + roman.get(ch[i+1]) - roman.get(ch[i]);
i = i + 2;
}
else
{
result = result + roman.get(ch[i]);
i = i + 1;
}
}
return result;
}
}