LeetCode 13 questions Roman numerals to integers
1. Title Description
- Convert Roman numerals to integers
Roman numerals contain the following seven characters: I, V, X, L, C, D and M.
character | The numerical |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
For example, the Roman numeral 2 is written as II, which is two ones side by side. Write XII as X + II. Write XXVII as XX + V + II.
Usually, the smaller Roman numerals are to the right of the larger numerals. But there are exceptions, for example, 4 is not written as IIII, it’s written as IV. The number 1 is to the left of the number 5 and represents the number 4 when the larger number 5 decreases by 1. Similarly, the number 9 represents IX. This particular rule applies only to the following six situations:
I can be put to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be put to the left of D (500) and M (1000) to represent 400 and 900. Given a Roman numeral, convert it to an integer. Make sure the input is in the range of 1 to 3999.
Example 1:
Input: “III” Output: 3 Example 2:
Input: “IV” Output: 4
Input: “IX” Output: 9 Example 4:
L = 50, V= 5, III = 3. Example 5:
Input: “MCMXCIV” Output: 1994 Explanation: M = 1000, CM = 900, XC = 90, IV = 4.
Tip:
1 < = s.l ength < = 15 s only contain characters (‘ I ‘, ‘V’ and ‘X’, ‘L’, ‘C’, ‘D’, ‘M’) subject data guarantee s is a valid Roman numerals, It indicates that the integer is in the range [1, 3999] and all the test cases given in the question comply with the Roman numerals writing rules, and there will be no cross. Examples like IL and IM don’t fit the question, 49 should be XLIX, 999 should be CMXCIX.
Ii. Analysis of Ideas:
All combinations of numbers are cumulative. All anomalies can be eliminated by subtracting the current digit less than the next digit. The final sum is the result.
Iii. AC code: —
class Solution {
public int romanToInt(String s) {
int sum = 0;
Map<Character,Integer> collectMap = new HashMap<>();
collectMap.put('I'.1);
collectMap.put('V'.5);
collectMap.put('X'.10);
collectMap.put('L'.50);
collectMap.put('C'.100);
collectMap.put('D'.500);
collectMap.put('M'.1000);
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i == chars.length-1){
sum+=collectMap.get(chars[i]);
}else {
if (collectMap.get(chars[i])<collectMap.get(chars[i+1])){
sum-=collectMap.get(chars[i]);
}else{ sum+=collectMap.get(chars[i]); }}}returnsum; }}Copy the code
Iv. Summary:
Map comparison consumes space and time, can be replaced with switch case;
“This article is participating in the” Gold Digging march Campaign “, click to see the details of the campaign.”