Integer to Roman

來源:互聯網
上載者:User

標籤:

Given an integer, convert it to a roman numeral.

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

將整數轉化為羅馬數字。需要知道一些羅馬數位規則,具體見維基百科。主要需要注意的是左減的存在,同時左減也僅限I、X、C三個數字。為了避免左減帶來的運算複雜度,可以把左減的組合直接表示出來。直接擴充原有的數字情況。

I: 1

IV: 4
V: 5IX: 9
X: 10XL: 40
L: 50XC: 90
C: 100CD: 400
D: 500CM: 900
M: 1000

 將這些組合的數字和十進位裡面的計算對等起來,就非常簡單,有則將字母或者字母組合添加入字串中,沒有則繼續向低位值推進。同時因為加上組合出來的數字表,相鄰之間的值最大為四倍關係,有效避免了同一數字重複出現三次以上的情形,符合羅馬數位規定。

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

代碼如下:

 
class Solution(object):    def intToRoman(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 = ‘‘        for i in range(len(map)):            if num >= map[i]:                val = num/map[i]                ret+= key[i]*val                num -= map[i]*val                    return ret 

 

Integer to Roman

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.