描述
思路1
1 首先将字符串变为字符数组,然后从最右边往左边遍历
2 一共7种字符,除了第一种’I’之外,其余的都可能出现像"IV"的情况,因此在这6种情况里,每次都判断下是否出现了像"IV"的情况
3 这里需注意边界问题,在判断"IV"这种情况时,指向字符数组的下标要判断是否是>=0的
思路1 代码
public class Solution {
public static int romanToInt(String s) {
char[] arrayS = s.toCharArray();
int i = arrayS.length - 1;//i指向字符数组的最后一个
int result = 0;
while (i >= 0) {
//I' == 1
if (arrayS[i] == 'I') {
result++;
i--;
continue;
}
//V' == 5
if (arrayS[i] == 'V') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'I')) { //'IV' == 4
result += 4;
i = i - 2;
} else {
result += 5;
i--;
}
continue;
}
//'X' == 10
if (arrayS[i] == 'X') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'I')) { //'IX' == 9
result += 9;
i = i - 2;
} else {
result += 10;
i--;
}
continue;
}
//'L' == 50
if (arrayS[i] == 'L') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'X')) { //'XL' == 40
result += 40;
i = i - 2;
} else {//最多一个50
result += 50;
i--;
}
continue;
}
//'C' == 100
if (arrayS[i] == 'C') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'X')) { //'XC' == 90
result += 90;
i = i - 2;
} else {
result += 100;
i--;
}
continue;
}
//'D' == 500
if (arrayS[i] == 'D') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'C')) { //'CD' == 400
result += 400;
i = i - 2;
} else {
result += 500;
i--;
}
continue;
}
//'M' == 1000
if (arrayS[i] == 'M') {
if (((i-1) >= 0) && (arrayS[i - 1] == 'C')) { //'CM' == 900
result += 900;
i = i - 2;
} else {
result += 1000;
i--;
}
continue;
}
}
return result;
}
}
思路2 直接上代码吧 这种比较秀
class Solution {
public int romanToInt(String s) {
s = s.replace("IV","a");
s = s.replace("IX","b");
s = s.replace("XL","c");
s = s.replace("XC","d");
s = s.replace("CD","e");
s = s.replace("CM","f");
int res = 0;
for (int i = 0; i < s.length(); i++) {
res += getValue(s.charAt(i));
}
return res;
}
public int getValue(char c) {
switch(c) {
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;
case 'a': return 4;
case 'b': return 9;
case 'c': return 40;
case 'd': return 90;
case 'e': return 400;
case 'f': return 900;
}
return 0;
}
}