Question: Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Analysis: 该问题是将输入的罗马数字的字符串转化为整数。 方法:从左到右依次扫描字符串,需要三个变量:temp记录分段数字, lastv表示刚刚扫描过的数字, curv表示当前正在扫描的数字。
1. 若lastv == curv,则记录变量加上当前字符;
2. 若lastv < curv,则当前字符减去记录变量记录下的值;
3.若lastv > curv,记录变量直接加到结果中。
Answer:
public class Solution { public int romanToInt(String s) { if(s == null || s.length() == 0) return 0; int sum = 0; int temp = charToInt(s.charAt(0)); int lastv = temp; for(int i=1; i<s.length(); i++){ char c = s.charAt(i); int curv = charToInt(c); if(lastv == curv) temp += curv; else if(lastv < curv){ temp = curv - temp; } else { sum += temp; temp = curv; } lastv = curv; } sum += temp; return sum; } private int charToInt(char c) { // TODO Auto-generated method stub 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; default: return 0; } } }