leetcode 13. 罗马数字转整数
正经解法
把一个小值放在大值的左边,就是做减法,否则为加法.
import java.util.*;
class Solution {
public int romanToInt(String s) {
int sum = 0;
int preNum = getValue(s.charAt(0));
for(int i = 1;i < s.length(); i ++) {
int num = getValue(s.charAt(i));
if(preNum < num) {
sum -= preNum;
} else {
sum += preNum;
}
preNum = num;
}
sum += preNum;
return sum;
}
private int getValue(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}
替换法
比较取巧,好理解好实现,但是replace比较耗时
class Solution {
public int romanToInt(String s) {
s = s.replaceAll("IV", "IIII");
s = s.replaceAll("IX", "VIIII");
s = s.replaceAll("XL", "XXXX");
s = s.replaceAll("XC", "LXXXX");
s = s.replaceAll("CD", "CCCC");
s = s.replaceAll("CM", "DCCCC");
char[] chars = s.toCharArray();
int ans = 0;
for (char c : chars) {
ans = ans + becomeInt(c);
}
return ans;
}
public int becomeInt(char c) {
if (c == 'I') return 1;
if (c == 'V') return 5;
if (c == 'X') return 10;
if (c == 'L') return 50;
if (c == 'C') return 100;
if (c == 'D') return 500;
if (c == 'M') return 1000;
return 0;
}
}