Roman numerals contain the following seven characters: I, V, X, L, C, D, and M. Character value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, the Roman numeral 2 is written as "II", that is, two parallel ones. 12 write XII, that is, X + II. 27 write XXVII, that is, XX + V + II.
Example 1:
Input: "III" Output: 3
Example 2:
Input: "IV" Output: 4
*How to solve the problem: judge whether the number represented by the previous digit is smaller than the position, and subtract the number represented by the previous digit if it is smaller *(Note: since traversing the previous bit is adding the previous bit to res, you need to subtract twice the number represented by the previous bit)
public int romanToInt(String s) { int res = 0 , i=0; int length = s.length(); int pre = 0; while (i < length){ switch (s.charAt(i)){ case 'M': if (pre<1000){ res +=1000-pre*2; }else{ res +=1000; } pre = 1000; break; case 'D': if (pre<500){ res +=500-pre*2; }else{ res +=500; } pre = 500; break; case 'C': if (pre<100){ res +=100-pre*2; }else{ res +=100; } pre = 100; break; case 'L': if (pre<50){ res +=50-pre*2; }else{ res +=50; } pre = 50; break; case 'X': if (pre<10){ res +=10-pre*2; }else{ res +=10; } pre = 10; break; case 'V': if (pre<5){ res +=5-pre*2; }else{ res +=5; } pre = 5; break; case 'I': if (pre<1){ res +=1-pre*2; }else{ res +=1; } pre = 1; break; } i++; } return res; }