No.013: Roman to Integer, no.013roman
Question:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Official difficulty:
Easy
Translation:
A given Roman digit is translated into an integer of Arabic numerals. The input roman numerals range from 1 to 3999.
Ideas:
1. For the Rome digital rules, see Chapter No. 012.
2. The input does not consider the form of a non-Roman number, or the incorrect form of a Roman number (such as IVI ).
3. You need a Roman character to convert it into a number dictionary.
4. Read the roman numerals at the corresponding position of the input string in sequence and accumulate them.
5. Special situations 4 and 9 need to be considered. Maintain a previous int variable to record the number represented by the previous Roman string. It is found that the current number is 5 times or 10 times the value of previous, in the case of 4 and 9, subtract back.
Possible difficulties in solving problems:
1. In the case of 4 and 9, the dropped value is twice that of previous, because previous has been accumulated once before.
2. When previous is assigned an initial value, do not affect the first calculation. Because the current/previous value is determined, a negative value or an I value can be added! A condition of = 0 will be discarded from the first loop.
3. when creating a dictionary method, the switch-case-default structure is generally adopted. Before Java 7, the variable type in the brackets after the switch cannot be of the String type, therefore, use the char type to save the Roman numerals.
Solution code:
1 // do not consider invalid Rome String format 2 private static int method (String roman) {3 char [] array = roman. toCharArray (); 4 int sum = 0; 5 // The value represented by the previous string. The initial value is not affected by the first calculation of 6 int previous =-1; 7 int current; 8 for (int I = 0; I <array. length; I ++) {9 current = romanDict (array [I]); 10 // special 4, 9 handle 11 if (current/previous = 5 | current/previous = 10) {12 sum-= 2 * previous; 13} 14 sum + = current; 15 previous = current; 16} 17 return sum; 18} 19 20 // Rome numeric conversion dictionary 21 private static int romanDict (char str) {22 switch (str) {23 case 'I': 24 return 1; 25 case 'V': 26 return 5; 27 case 'X': 28 return 10; 29 case 'l': 30 return 50; 31 case 'C': 32 return 100; 33 case 'D': 34 return 500; 35 case 'M': 36 return 1000; 37 default: 38 return 0; 39} 40}View Code
Test Code address:
Https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q013.java
LeetCode address:
Https://leetcode.com/problems/roman-to-integer/
PS: If you have any incorrect or more efficient methods, please leave a message. Thank you!