Roman to Integer Leetcode Python

Source: Internet
Author: User

Given a Roman numeral, convert it to an integer.


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

The practice of this problem and the previous one interger to Roman similar to build a dictionary to query.

1. Reverse the string first

2. Use one last to save the previous digit

3. If the last digit is greater than the current digit, subtract the value by twice times digit otherwise add.

For example, iv inversion is the VI direct plus after equals 6 actual value of 4 need to subtract twice times 1


The code is as follows

Class solution:    # @return An integer    def romantoint (self, s):        dict={' M ': +, ' D ': $, ' C ': +, ' L ': ' X ' : Ten, ' V ': 5, ' I ': 1}        last=none        sum=0        s=s[::-1] for        Elem in S:            if Last and Dict[last]>dict[elem]:                Sum-=2*dict[elem]            Sum+=dict[elem]            last=elem        return sum                        
Reference http://www.cnblogs.com/zuoyuan/p/3779688.html

Roman to Integer Leetcode Python

Related Article

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.