原题:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
即将罗马数字转换成整数。
思考过程:
刚做完Integer To Roman,本来打算将原来的过程逆一下:从字符串最后一个开始,向前遍历。后来发现没这个必要:罗马数字好就好在不论从前面读还是从后面读都没问题,要是现在的阿拉伯数字,你试试?所以打算从前面遍历。
解题思路:
String[] romanNumber = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int[] integerNumber = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 ,1};
还是先把这个”表“亮到这。先从”M“开始,看字符串开始有没有”M“,如果没有就找”CM“,如果有,给int res加上1000,并且跳过这个”M“,从下个字符开始。当然如果romainNumber[i]长度为2,就判断s的眼前两个字符组成的字符串。以此类推。一开始大意:字符串比较没有用equal的方法。后来在while循环体没有判断是否越界。
结果代码:
public int romanToInt(String s) { int res = 0,location = 0;//location标记遍历到s的什么位置 String[] romanNumber = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int[] integerNumber = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 ,1}; for (int i = 0;location < s.length();i++){ if (romanNumber[i].length() == 2) while ((location < s.length() - 1) && (s.substring(location,location + 2).equals(romanNumber[i]))){//一定要判断是否越界,对字符串操作不像对整数,进行大于零判断就可以。 res += integerNumber[i]; location += 2; } else while ((location < s.length()) && (s.substring(location,location + 1).equals(romanNumber[i]))){ res += integerNumber[i]; location += 1; } } return res; }