LeetCode -- Roman to Integer, Roman numerals
This topic is very simple. If you don't know the relationship between numbers and Roman numerals, you won't be able to start.
Question:
Principles and ideas: the Roman numerals have the following symbols:
Basic Characters |
I |
V |
X |
L |
C |
D |
M |
Corresponding to Arabic numerals |
1 |
5 |
10 |
50 |
100 |
500 |
1000 |
Counting rule: Second, the rule for the conversion of Roman numerals to Arabic numerals (limited to less than 3999): traverse the roman numerals from the front to the back. If a number is smaller than the previous one, add this number. Otherwise, double the previous number and add this number.
Code scheme:
import java.util.Map;import java.util.HashMap;public class Solution { public int romanToInt(String s) { Map<Character,Integer> map=new HashMap<Character,Integer>();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); int i, total, pre, cur; total = map.get(s.charAt(0)); for (i = 1; i < s.length(); i++) { pre = map.get(s.charAt(i - 1)); cur = map.get(s.charAt(i)); if (cur <= pre) { total += cur; } else { total = total - pre * 2 + cur; } } return total; }}