leetcode [#13]

目录

题目

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Solution {
public int romanToInt(String s) {
int len = s.length();
int result = 0;
if(s == null || len == 0) return 0;
for(int i = 0; i < len; i++){
if(s.charAt(i) == 'M'){
result += 1000;
} else if(s.charAt(i) == 'V'){
result += 5;
} else if(s.charAt(i) == 'L'){
result += 50;
} else if(s.charAt(i) == 'D'){
result += 500;
} else if(s.charAt(i) == 'I'){
if(i == (len - 1)){
result += 1;
} else {
if(s.charAt(i+1) == 'I'){
result += 1;
} else {
result -= 1;
}
}
} else if(s.charAt(i) == 'X'){
if(i == (len - 1)){
result += 10;
} else {
if(s.charAt(i+1) == 'X' || s.charAt(i+1) == 'V' || s.charAt(i+1) == 'I'){
result += 10;
} else {
result -= 10;
}
}
} else if(s.charAt(i) == 'C'){
if(i == (len - 1)){
result += 100;
} else {
if(s.charAt(i+1) == 'C' || s.charAt(i+1) == 'L' || s.charAt(i+1) == 'X' || s.charAt(i+1) == 'V' || s.charAt(i+1) == 'I'){
result += 100;
} else {
result -= 100;
}
}
}
}
return result;
}
}

注意事项

  1. 明确罗马数字表示方法:

    a. 共有I X C M V L D七种字符,分别代表1,10,100,1000,5,50,500
    b. 给定一串罗马数字,其代表的数字是各位数字求和,但有特殊情况:当数字为I,X,C时,如果后面的罗马数字代表的数据比当前位大,则当前位作为减数,否则正常作为加数。

  2. 根据上述规律遍历一遍字符串即可得到结果。