"Leetcode-easy" Roman to Integer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.