Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Analysis:
First, we are familiar with the following Roman number composition rules:
Roman numerals have a total of 7 symbols, ' I ': 1, ' V ': 5, ' X ': Ten, ' L ': ' C ': +, ' D ': $, ' M ': 1000. If the small number of characters appears after the large number of characters, then we can directly add the array represented by the number of characters to the result. However, in Roman digital notation, there are 3 special cases which need to be discussed separately:
1) A ' I ' appears before ' V ' or ' X ', representing 4 and 9, respectively.
2) An ' X ' appears before ' L ' or ' C ', representing 40 and 90, respectively.
3) A ' C ' appears before ' D ' or ' M ', representing 400 and 900, respectively.
In conclusion, there are two types of discussions that we can implement, that is, whether the number represented by the current number is greater than the number represented by the previous digit.
The code is as follows:
classSolution { Public: intRomantoint (strings) {intresult =0; for(inti =0; I < s.length (); i++){ if(I >0&& map (s[i]) > Map (s[i-1]) Result+ = map (S[i])-2*map (s[i-1]); ElseResult + =map (s[i]); } returnresult; } intMapCharc) { Switch(c) { Case 'I':return 1; Case 'V':return 5; Case 'X':return Ten; Case 'L':return -; Case 'C':return -; Case 'D':return -; Case 'M':return +; default:return 0; } }};
Leetcode:roman to Integer