Test instructions
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Analysis:
Start preparing to divide the Roman numerals into thousands, hundred, and so on, but the code is too complex to actually manipulate, and the logic that you think of is problematic.
The last way is to iterate through the characters from the front to the back, and judge to see if the characters are together with the preceding characters "decimal numbers on the left of the large number";
Then addend to the results in turn.
Code:
1 classSolution {2 Public:3 intRomantoint (strings) {4 intresult =0;5 for(inti =0; I < s.size (); ++i) {6 if(S[i] = ='M') {7 ifI1>=0&& s[i-1] =='C') {8Result + = -;9 }Ten Else { OneResult + = +; A } - } - if(S[i] = ='D') { the ifI1>=0&& s[i-1] =='C') { -Result + = -; - } - Else { +Result + = -; - } + } A if(S[i] = ='C') { at ifI1>=0&& s[i-1] =='X') { -Result + = the; - } - Else { -Result + = -; - } in } - if(S[i] = ='L') { to ifI1>=0&& s[i-1] =='X') { +Result + = -; - } the Else { *Result + = -; $ }Panax Notoginseng } - if(S[i] = ='X') { the ifI1>=0&& s[i-1] =='I') { +Result + =8; A } the Else { +Result + =Ten; - } $ } $ if(S[i] = ='V') { - ifI1>=0&& s[i-1] =='I') { -Result + =3; the } - Else {WuyiResult + =5; the } - } Wu if(S[i] = ='I'){ -Result + =1; About } $ } - returnresult; - } -};
Leetcode13 Roman to Integer