Leetcode13 Roman to Integer

Source: Internet
Author: User

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

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.