Leetcode: Roman numeral to integer "13" title description
The Roman numerals contain the following seven characters:,,,, I
V
X
L
C
, D
and M
.
Character value I 1V 5X 10L 50C 100D 500M 1000
For example, the Roman numeral 2 is written II
, that is, two parallel 1. 12 Write XII
, that is X
+ II
. 27 Write XXVII
, that 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 as 4 not IIII
to write, but IV
. The number 1 is on the left side of the number 5, the number represented is equal to the large number 5 decreases the number 1 gets the value 4. Similarly, the number 9 is represented as IX
. This special rule applies only to the following six cases:
I
Can be placed on V
X
the left side of (5) and (10) to represent 4 and 9.
X
Can be placed on L
C
the left side of (50) and (100) to represent 40 and 90.
C
Can be placed on D
M
the left side of (500) and (1000) to represent 400 and 900.
Given a Roman number, convert it to an integer. The input is guaranteed to be within the range of 1 to 3999.
Example 1:
Input: "III" output: 3
Example 2:
Input: "IV" output: 4
Example 3:
Input: "IX" output: 9
Example 4:
Input: "LVIII" output: 58 Explanation: L = 3, v= 5, Iii.
Example 5:
Input: "MCMXCIV" output: 1994 Explanation: M = +, CM = =, XC = all, IV = 4.
Problem analysis
Brush the question expensive in insist, hope oneself can keep brush problem, do not become often determined person, Hiahia.
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 as IV, which is 4 without IIII. If there is no special case, we will add up from left to right, and we are dealing with this particular case.
each time we compare to the previous element, if an element is greater than the previous one, there must be a 4,9,40. This number , to want this value first is the right minus the left side , such as cm (900=1000-100), but the figure minus twice times the C, why? Each time compared to the previous element, then when we reach the CM C, because C is M on the left, then it must accumulate C, the left of M, C, at this time to subtract, accumulate (c-m), this will be more calculate a C, so to remove more than a C.
Java
Class Solution {public int romantoint (String s) { if (s==null| | S.length () ==0) return 0; int res = Tonumber (S.charat (0)); for (int j=1;j<s.length (); j + +) { if (Tonumber (S.charat (j)) >tonumber (S.charat (j-1))) res=res+ ( Tonumber (S.charat (j)) -2*tonumber (S.charat (j-1))); else res=res+ (Tonumber (S.charat (j))); return res; } public int Tonumber (char c) { int res = 0; Switch (c) {case ' I ': return 1; Case ' V ': return 5; Case ' X ': return ten; Case ' L ': return; Case ' C ': return; Case ' D ': return; Case ' M ': return; } return res; }}
Leetcode: Roman numerals to integers "13"