The number contains the following seven characters:I
,V
,X
,L
,C
,D
AndM
.
Character value I 1 V 5x 10l 50C 100d 500 m 1000
For example, write the number 2 in RomeII
, That is, two parallel 1. 12 writeXII
, That isX
+II
. 27 writeXXVII
, That isXX
+V
+II
.
Generally, a small number is on the right of a large number. But there are also special cases, for example, do not write 4IIII
,IV
. The number 1 is on the left of number 5, and the number is equal to the number 5. Reduce the number 1 to get the value 4. Similarly, Number 9 indicatesIX
. This special rule applies only to the following six cases:
I
Can be placed inV
(5) andX
The left side of (10) indicates 4 and 9.
X
Can be placed inL
(50) andC
The left side of (100) indicates 40 and 90.
C
Can be placed inD
(500) andM
The left side of (1000) indicates 400 and 900.
Converts a roman number to an integer. Make sure that the input is 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 = 50, V = 5, III = 3.
Example 5:
Input: "mcmxciv" output: 1994 explanation: M = 1000, Cm = 900, XC = 90, IV = 4.
Answer:
class Solution { public int romanToInt(String s) { int sum=0; char[] schar=s.toCharArray(); Map map =new HashMap(); map.put(‘I‘,1); map.put(‘V‘,5); map.put(‘X‘,10); map.put(‘L‘,50); map.put(‘C‘,100); map.put(‘D‘,500); map.put(‘M‘,1000); for (int i = 0; i <schar.length ; i++) { if (i<schar.length-1) { //IV if ((int) map.get(schar[i]) == 1 && (int) map.get(schar[i + 1]) == 5) { sum -= 2; } //IX if ((int) map.get(schar[i]) == 1 && (int) map.get(schar[i + 1]) == 10) { sum -= 2; } //XL if ((int) map.get(schar[i]) == 10 && (int) map.get(schar[i + 1]) == 50) { sum -= 20; } //XC if ((int) map.get(schar[i]) == 10 && (int) map.get(schar[i + 1]) == 100) { sum -= 20; } //CD if ((int) map.get(schar[i]) == 100 && (int) map.get(schar[i + 1]) == 500) { sum -= 200; } //CM if ((int) map.get(schar[i]) == 100 && (int) map.get(schar[i + 1]) == 1000) { sum -= 200; } } sum +=(int) map.get(schar[i]); } return sum; }}
Submission result:
Leetcode record-convert the number of Rome to an integer