Leetcode_num14_Roman to Integer

來源:互聯網
上載者:User

標籤:leetcode   字串轉換   

題目:

Given a roman numeral, convert it to an integer.

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

題目意思很簡單,即將一個羅馬數位字串,轉化為整數。

首先我們需要對羅馬數字有一個基本的認識,由於題目已將數字大小限定在1~3999,所以我們只需考慮千位元即可,無需涉及數位分段等複雜的問題。

下面簡要列出羅馬數字中的單位:‘I‘ 1; ‘V‘ 5; ‘X‘ 10; ‘L‘ 50 ; ‘C‘ 100; ‘D‘ 500; ‘M‘ 1000

羅馬數位大小即是將其中所包含字元所代表的的數字求和,其中數位組合規律為: I X C 會因位置的不同而加減其值。舉個栗子,IV的值為4,而VI的值為6;CD的值為400,而DC的值為600。V L D M在1~3999的範圍內則不存在該問題。

最終選擇了一個只需遍曆一次字串的方法,即從末尾開始遍曆羅馬數字字串,若出現 I(X ,C) ,如果已遍曆部分的值高於V(L, D),則在已有結果中減去I(X ,C)的值,反之,則加上。

總結一句,此題的關鍵在於找規律,最後上代碼咯~

class Solution:    # @return an integer    def romanToInt(self, s):        L=len(s)        res=0        for i in range(L-1,-1,-1):            a=s[i]            if a=='I':                if res>=5:                    res-=1                else:                    res+=1            elif a=='V':                res+=5            elif a=='X':                if res>=50:                    res-=10                else:                    res+=10            elif a=='L':                res+=50            elif a=='C':                if res>=500:                    res-=100                else:                    res+=100            elif a=='D':                res+=500            elif a=='M':                res+=1000        return res


Leetcode_num14_Roman to Integer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.