Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
The topic is short, but the difficulty is still there.
First of all, we need to understand how the Roman numbers are counted, and when you understand this you will have to go a lot less detours.
Roman numerals are a type of digital used before they are introduced. Roman numerals use seven Roman letters as numbers, i.e. Ⅰ (1), X (10), C (100), M (1000), V (5), L (50), D (500). Methods of Counting:
- The same number ligatures, the number represented is equal to the number of these numbers added, such as ⅲ=3;
- The small number is on the right side of the large number, and the number represented is equal to the number added to the number, such as ⅷ=8, ⅻ=12;
- The small numbers (limited to Ⅰ, X, and C) are on the left side of the large number, and the number represented is equal to the number of large numbers reduced, such as ⅳ=4, ⅸ=9;
- Draw a horizontal line on top of a number, indicating that the number is increased by 1,000 times, such as = 5000.
So the first thing to do first is to build a basic mapping, Ⅰ (1), X (10), C (100), M (1000), V (5), L (50), D (500), and of course I use a map of my own preference.
To build such a dictionary, but in the process of using map, I found myself having a very important place to ignore, is to use subscript to value the time of its type is actually mapped_type rather than value_type , only with
The iterator is worth the time to fetch the second, so here we use the Find function, and the Findfunction returns the iterators that are found based on the key value , so you get value_type, so I just started to compare them directly.
Then is the comparison size, small on the addition of good, big time to take a large value reduction value, this time to jump forward a i=i-2
Fortunately, when the Roman numeral value is reduced, there are only two bits, otherwise it will be more complicated. Attach the code, make it OK.
1 classSolution {2 Public:3 intRomantoint (strings) {4map<string,int>Roman;5 stringTempb,tempf;6 intr,l;7roman["I"]=1;8roman["X"]=Ten;9roman["C"]= -;Tenroman["M"]= +; Oneroman["V"]=5; Aroman["L"]= -; -roman["D"]= -; - intresult=0; the intLength=s.length (); - if(length==0)return 0; - for(inti=length-1; i>=0;){ -tempb=S[i]; +tempf=s[i-1]; - +Auto it=Roman.find (TEMPB); AAuto itfront=Roman.find (TEMPF); at if((*it). second<= (*Itfront). Second) { -result+= (*it). Second; -i--;} - Else{result=result+ (*it). second-(*Itfront). Second; -i=i-2; - } in - } to returnresult; + - the } *};
Leetcode Roman to Integer