Conversion of Roman numerals to integers
* 1, the basic number Ⅰ, X, C of any one, the number of its own use, or put on the right of the large number of the number of use, can not exceed three; on the left of the large number can only use one;
* 2, can not be the basic number of V, L, D of any one as a decimal place on the left of the large number of the method of subtracting the number of methods to be placed on the right side of the large number of the number of ways, only one;
* 3, V and X left small numbers can only be used Ⅰ;
* 4, L and C small numbers on the left can only be used x;
* The small numbers on the left of 5, D and M can only be used in C.
Idea: The sequential read character, if the previous one is greater than the previous bit, minus twice times the previous bit, because the previous one was added. Otherwise, the number corresponding to that bit is added.
1 Public intRomantoint (String s) {2 intResult=tonum (S.charat (0));3 for(intI=1;i<s.length (); i++){4 if(Tonum (S.charat (i-1)) <Tonum (S.charat (i))) {5Result+=tonum (S.charat (i)) -2*tonum (S.charat (i-1));//why subtract twice times from the previous one because it is preceded by one. can analyze xix=19;6}Else{7result+=Tonum (S.charat (i));8 }9 }Ten returnresult; One } A intTonum (CharCH) {//or by storing it in the HashMap. - intN=0; - Switch(CH) { the Case' I ':return1; - Case' V ':return5; - Case' X ':return10; - Case' L ':return50; + Case' C ':return100; - Case' D ':return500; + Case' M ':return1000; A } at returnN; -}
"Leetcode-easy" Roman to Integer