Math
String
Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
What is Roman Numeral?
my Solution:
public class Solution {
public int romanToInt(String s) {
int[] priority = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'I':
priority[i] = 1;
break;
case 'V':
priority[i] = 5;
break;
case 'X':
priority[i] = 10;
break;
case 'L':
priority[i] = 50;
break;
case 'C':
priority[i] = 100;
break;
case 'D':
priority[i] = 500;
break;
case 'M':
priority[i] = 1000;
break;
}
}
int output = 0;
for (int i = 1; i < priority.length; i++) {
if (priority[i] > priority[i - 1]) {
output -= priority[i-1];
} else {
output += priority[i-1];
}
}
output += priority[priority.length - 1];
return output;
}
}
稍好一点的做法:
public static int romanToInt(String s) {
int res = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
switch (c) {
case 'I':
res += (res >= 5 ? -1 : 1);
break;
case 'V':
res += 5;
break;
case 'X':
res += 10 * (res >= 50 ? -1 : 1);
break;
case 'L':
res += 50;
break;
case 'C':
res += 100 * (res >= 500 ? -1 : 1);
break;
case 'D':
res += 500;
break;
case 'M':
res += 1000;
break;
}
}
return res;
}