[Leetcode] [Python] Roman to Integer

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
https://oj.leetcode.com/problems/roman-to-integer/
Roman to Integer

Given a Roman numeral, convert it to an integer.

Input is guaranteed to being within the range from 1 to 3999.
===comments by dabay===
First Google a little bit of Roman numerals:
I-1
V-5
X-10
L-50
C-100
D-500
M-1000
The main problem is to consider a number of 4,40 and other representations.

You can go from right to left, and then process it in turn:
This number is subtracted when the number represented by this letter is smaller than the latter;
‘‘‘

Class Solution:
# @return An integer
def romantoint (self, s):
Roman_dict = {"I": 1, "V": 5, "X": Ten, "L": +, "C": +, "D": $, "M": 1000}
If Len (s) = = 0:
return 0
Value = 0
For i in Xrange (Len (s)-1,-1,-1):
If I < Len (s)-1 and Roman_dict[s[i]] < roman_dict[s[i+1]]:
Value = Value-roman_dict[s[i]]
Else
Value = value + roman_dict[s[i]]
return value


def main ():
s = solution ()
Print S.romantoint ("Mcmxcix")


if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)


[Leetcode] [Python] 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.