class Solution {
public int romanToInt(String s) {
if(s == null || s.length() == 0) return 0;
int result = 0;
if(s.indexOf("IV") != -1) result -= 2;//没有该元素的时候才返回-1
if(s.indexOf("IX") != -1) result -= 2;
if(s.indexOf("XL") != -1) result -= 20;
if(s.indexOf("XC") != -1) result -= 20;
if(s.indexOf("CD") != -1) result -= 200;
if(s.indexOf("CM") != -1) result -= 200;
char[] c = s.toCharArray();
for(int i = 0; i < c.length; i++){
if(c[i] == 'I') result += 1;
else if(c[i] =='V') result += 5;
else if(c[i] =='X') result += 10;
else if(c[i] =='L') result += 50;
else if(c[i] =='C') result += 100;
else if(c[i] =='D') result += 500;
else if(c[i] =='M') result += 1000;
}
return result;
}
}
归纳:
indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1,特殊的是,罗马数字表示的IV、IX等只会出现一次
本文提供了一种将罗马数字转换为整数的方法。通过分析特定组合(如IV、IX等)并利用indexOf方法查找这些组合的存在与否来调整最终结果。此外,还遍历字符串中的每个字符以累加其对应的数值。
1901

被折叠的 条评论
为什么被折叠?



