Integer to Roman

Source: Internet
Author: User

Given an integer, convert it to a Roman numeral.

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

Converts an integer to Roman numerals. Need to know some rules of Roman numerals, see Wikipedia. The main need to pay attention to is the existence of the left minus, while the left minus also limited to I, X, c three numbers. In order to avoid the computational complexity caused by left subtraction, the combination of left subtraction can be expressed directly. Direct expansion of the original digital situation.

I:1

Iv:4
V:5ix:9
X:10xl:40
L:50xc:90
c:100cd:400
d:500cm:900
m:1000

It is very simple to combine the numbers of these combinations with the computations in decimal, and then add the letters or combinations of letters to the string, and then continue to advance to the low values. At the same time, because of the combination of the number table, the value of adjacent to the maximum of four times times the relationship, effectively avoid the same number repeated more than three times, in line with the provisions of Roman numerals.

s = 3978

3978/1000 = 3:mmm978> (1000-100), 998/900 = 1:cm78< (100-10), 78/50 = 1:l28< (50-10), 28/10 = XX8< (100-1), 8/5 = 1:v
3< (5-1), 3/1 = 3:iiiret = MMMCMLXXVII

The code is as follows:

classsolution (object):defInttoroman (self, num):""": Type Num:int:rtype:str"""Map= [1000,900,500,400,100,90,50,40,10,9,5,4,1] Key= ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] RET="'         forIinchRange (len (map)):ifNum >=Map[i]: Val= num/Map[i] ret+ = key[i]*Val Num-= map[i]*ValreturnRet

Integer to Roman

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.