Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Analysis:
The tricky in this problem is that Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases, to avoid four characters being repeated in succession (such as IIII or XXXX) these can be reduced using subtractive notation as follows:
- the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX respectively)
- X can be placed before L and C to make 40 (XL) and 90 (XC respectively)
- C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern
An example using the above rules would be 1904: this is composed of 1 (one thousand), 9 (nine hundreds), 0 (zero tens), and 4 (four units). To write the Roman numeral, each of the non-zero digits should be treated separately. Thus 1,000 = M, 900 = CM, and 4 =IV. Therefore, 1904 is MCMIV.
The solution is that add up every character, if the previous character is smaller than the current character then subtract the previous character twice.
Solution:
1: public class Solution {
2: public int romanToInt(String s) {
3: if(s==null) return 0;
4: if(s.length()==1) return getInt(s.charAt(0));
5: int pre=s.charAt(0);
6: int cur=0;
7: int total=s.charAt(0);
8: for(int i=1;i<s.length();i++)
9: {
10: cur=getInt(s.charAt(i));
11: total+=cur;
12: if(pre<cur)
13: total=total-pre*2;
14: pre=cur;
15: }
16: return total;
17: }
18: public int getInt(char digit)
19: {
20: int result=0;
21: switch (digit)
22: {
23: case 'I': result=1; break;
24: case 'V': result=5; break;
25: case 'X': result=10;break;
26: case 'L': result=50;break;
27: case 'C': result=100;break;
28: case 'D': result=500;break;
29: case 'M': result=1000;break;
30: }
31: return result;
32: }
33: }
Reference:
http://en.wikipedia.org/wiki/Roman_numerals