LeetCode-13. Roman to Integer

Source: Internet
Author: User

Topic:

Given a Roman numeral, convert it to an integer.

Input is guaranteed to being within the range from 1 to 3999.

Problem Solving Ideas:

The previous article has introduced the composition and calculation of Roman numerals, so it is easier to convert Roman numerals into integers.

The way I thought before was to judge the character from left to right and to subtract or other 1,10,100, but it was a lot simpler to see a right-to-left calculation.

When calculating from right to left, it is only necessary to determine whether the current number is not less than 5 or 50,500 when encountering 1,10,100.

C # code:

 Public classSolution { Public intRomantoint (strings) {intresult =0;  for(inti = s.length-1; I >=0; i--)        {            Switch(S[i]) { Case 'I': Result+ = (Result >=5) ? -1:1;  Break;  Case 'V': Result+=5;  Break;  Case 'X': Result+ = (Result >= -) ? -Ten:Ten;  Break;  Case 'L': Result+= -;  Break;  Case 'C': Result+ = (Result >= -) ? - -: -;  Break;  Case 'D': Result+= -;  Break;  Case 'M': Result+= +;  Break; default:                    return 0; }        }        returnresult; }}
View Code

LeetCode-13. 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.