题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
简述:
基本字符 |
I
|
V
|
X
|
L
|
C
|
D
|
M
|
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 |
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
1. 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
2. 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
3. 小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
4. 正常使用时、连写的数字重复不得超过三次;
思路1:用switch判断当前字符,并判断下一个字符是不是比当前的大。
代码1:
public int romanToInt(String s) {
int re=0;
int i=0;
while(i<s.length()){
switch(s.charAt(i)){
case 'I':
if(i+1<s.length()&&s.charAt(i+1)=='V'){
re+=4;
i+=2;
}else if(i+1<s.length()&&s.charAt(i+1)=='X'){
re+=9;
i+=2;
}else{
re+=1;
i++;
}
break;
case 'V':
re+=5;
i++;
break;
case 'X':
if(i+1<s.length()&&s.charAt(i+1)=='L'){
re+=40;
i+=2;
}else if(i+1<s.length()&&s.charAt(i+1)=='C'){
re+=90;
i+=2;
}else{
re+=10;
i++;
}
break;
case 'L':
re+=50;
i++;
break;
case 'C':
if(i+1<s.length()&&s.charAt(i+1)=='D'){
re+=400;
i+=2;
}else if(i+1<s.length()&&s.charAt(i+1)=='M'){
re+=900;
i+=2;
}else{
re+=100;
i++;
}
break;
case 'D':
re+=500;
i++;
break;
case 'M':
re+=1000;
i++;
break;
default:
break;
}
}
return re;
}
思路2:使用HashMap记录字符对应的数值。统计的时候从String末尾开始向前遍历。(速度会比思路1稍慢,但是好理解)
代码2:
public int romanToInt(String s) {
if(s == null || s.length() == 0) return 0;
int len = s.length();
HashMap<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 = map.get(s.charAt(len -1));
int pivot = result;
for(int i = len -2; i>= 0;i--){
int curr = map.get(s.charAt(i));
if(curr >= pivot){
result += curr;
}else{
result -= curr;
}
pivot = curr;
}
return result;
}