Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Topic Analysis: The topic seems relatively simple but behind the hidden many of the rules of the Roman numerals, access to some information the main rules are as follows
Roman Numeral Rules:
1, a total of 7 Roman numerals, namely I (1), V (5), X (10), L (50), C (100), D (500) and M (1000). There is no "0" in Roman numerals.
2, repetition: a Roman numeral repeats up to 3 times.
3, right plus left minus:
The smaller Roman numerals on the right side of the larger Roman numerals indicate large numbers plus small numbers.
The smaller Roman numerals on the left of the larger Roman numerals indicate that large numbers decrease the numbers.
4, the left minus the number has a limit, limited to I, X, C, and placed on the left of large numbers can only use one.
(*) The small digits to the left of V and X can only be used with Ⅰ.
(*) The small digits to the left of L and C can only be used with X.
(*) The small numbers on the left of D and M can only be used in C.
That's a good question to solve.
Algorithm analysis: Mainly through the hash table mapping, the other is very simple, on the AC code
public int Romantoint (String s) {//Security judgment if (s = = NULL | | s.length () = = 0) return 0;//hash table Hashmap<character, INTEGER&G T Nummap = new Hashmap<character, integer> () nummap.put (' I ', 1); Nummap.put (' V ', 5); Nummap.put (' X ', +); nummap.put (' L ', +); Nummap.put (' C ', +); Nummap.put (' D ', ' n '); Nummap.put (' M ', "n"); int len = S.length (); int result = Nummap.get (s . CharAt (Len-1)); for (int i = len-2; I >= 0; i--) {//Compare Roman characters if (Nummap.get (S.charat (i + 1)) <=nummap.get (S.charat (i)) {result = result + Nummap.get (S.charat (i));} else {result = Result-nummap.get (S.charat (i));}} return result;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Roman to Integer