forked from LeBW/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
28 lines (27 loc) · 812 Bytes
/
RomanToInteger.java
File metadata and controls
28 lines (27 loc) · 812 Bytes
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
/**
* @author LBW
*/
public class RomanToInteger {
public int romanToInt(String s) {
int result = 0;
int[] nums = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] dict = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int index = 0;
while (!s.equals("")) {
int targetSize = dict[index].length();
if (s.length() < targetSize) {
index++;
continue;
}
String target = s.substring(0, targetSize);
if (target.equals(dict[index])) {
s = s.substring(targetSize);
result += nums[index];
}
else {
index++;
}
}
return result;
}
}