Topic:
The Roman numerals contain the following seven characters: I, V, X, L,c,d and M. Character value I1V5XTenL -C -D -M +For example, Roman numerals2Write II, which is two parallel1。 AWrite XII, which is X + II. -Write as XXVII, which is XX + V +II. Usually, the number of Roman numerals is small and the numbers are on the right side of the large numbers. But there are exceptions, such as4Do not write IIII, but IV. Digital1In the digital5The left side, the number represented is equal to the large number5Decrease number1The resulting value4。 Similarly, the number9represented as IX. This special rule only applies to the following six cases: I can be placed in V (5) and X (Ten) to the left, to indicate4And9. X can be placed in L ( -) and C ( -) to the left, to indicate +And -. C can be placed in D ( -) and M ( +) to the left, to indicate -And the. Given a Roman number, convert it to an integer. Input ensures that the1To3999within the range. Example1: Enter:"III"Output:3Example2: Enter:"IV"Output:4Example3: Enter:"IX"Output:9Example4: Enter:"LVIII"Output: -Explanation: C= -, L = -, XXX = -, III =3. Example5: Enter:"MCMXCIV"Output:1994Explanation: M= +, CM = the, XC = -, IV =4.
Code implementation:
classSolution { Public: intRomantoint (strings) {inttagval[ the]; tagval['I'] =1; tagval['V'] =5; tagval['X'] =Ten; tagval['C'] = -; tagval['M'] = +; tagval['L'] = -; tagval['D'] = -; intval =0; for(inti =0; I < s.length (); i++){ if(i+1>= s.length () | | tagval[s[i+1]] <=Tagval[s[i]) Val+=Tagval[s[i]]; ElseVal-=Tagval[s[i]]; } returnVal; }};
"Simple Algorithm" 43. Roman numerals to integers