题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:1、首先百度了罗马数字的百度百科
基本字符
|
I
|
V
|
X
|
L
|
C
|
D
|
M
|
相应的阿拉伯数字表示为
|
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
public class RomantoInteger {
public int romanToInt(String s) {
char[] arr={'I','V','X','L','C','D','M'};
int[] num={1,5,10,50,100,500,1000};
HashMap<Character,Integer> map=new HashMap();
for(int i=0;i<arr.length;i++){
if(!map.containsKey(arr[i])){
map.put(arr[i], num[i]); //将罗马数字的基本类型和对应的整数存入map中
}
}
int value=0;
value+=map.get(s.charAt(0)); //获取第一个罗马数字的整数值
for(int i=1;i<s.length();i++){
int cur=map.get(s.charAt(i));
int pre=map.get(s.charAt(i-1));
if(cur<=pre){ //如果右边的罗马数字小于左边的,则直接相加
value+=cur;
}else{
value+=cur-2*pre; //如果右边的罗马数字大于左边的,由于左边的数字已经被前面加了一次,所以得减左边的两次
}
}
return value;
}
public static void main(String[] args) {
System.out.println(new RomantoInteger().romanToInt("MCMX"));
}
}