1. 程式人生 > >迴文數,羅馬數字轉整數

迴文數,羅馬數字轉整數

迴文數:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        x = str(x)
        return x[::-1] == x

題後感:

這個和反轉一樣直接想到用字串反轉然後對比

羅馬數字轉整數:

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = dict(
            I=1,
            V=5,
            X=10,
            L=50,
            C=100,
            D=500,
            M=1000,
            XL=40,
            XC=90,
            CD=400,
            CM=900,
            IV=4,
            IX=9,
        )
        i = 0
        res = 0
        while i < len(s):
            if s[i:i + 2] in d:
                res += d.get(s[i:i + 2])
                i += 2
            else:
                res += d.get(s[i])
                i += 1
        return res

題後感:

字串擷取的思路,一開始將兩位的羅馬數字也加入字典中,這樣方便判斷,給定的羅馬數字獲取兩位從左開始去字典中尋找,如果有就加上對應的數字,如果沒有就按一位去字典中尋找,如果有就相加