题目链接:罗马数字转整数
分析:
如图示意:
例如,我们给定一个罗马字母 CXCI,其对应的真实数字应该为191
在编程的时候,把每个字母逐个解析的话,是这样:C + X + C + I = 100 + 10 + 100 + 1 = 211
这样结果就不对了,应该是再减去差值,也就是20,才可以到的真实的值 191
所以说,在我们对给定的字符串遍历的时候,去逐个解析,遇到上述 IV、IX、XL、XC、CD、CM 的时候
都应该在最后遍历的结果后,减去差值,最终才可以得到真实的转换后的数值
代码实现:
public class Solution {
public int romanToInt(String input) {
if (input == null || input.length() == 0)
return 0;
int result = 0;
if (input.indexOf("CM") != -1)
result -= 200;
if (input.indexOf("CD") != -1)
result -= 200;
if (input.indexOf("XC") != -1)
result -= 20;
if (input.indexOf("XL") != -1)
result -= 20;
if (input.indexOf("IX") != -1)
result -= 2;
if (input.indexOf("IV") != -1)
result -= 2;
for (char c : input.toCharArray()) {
if (c == 'M')
result += 1000;
else if (c == 'D')
result += 500;
else if (c == 'C')
result += 100;
else if (c == 'L')
result += 50;
else if (c == 'X')
result += 10;
else if (c == 'V')
result += 5;
else if (c == 'I')
result += 1;
}
return result;
}
}