美文网首页
【Leetcode刷题】12. Integer to Roman

【Leetcode刷题】12. Integer to Roman

作者: maodoudou168 | 来源:发表于2019-03-16 19:25 被阅读0次

原始题目:

12. Integer to Roman

Medium

Roman numerals are represented by seven different symbols:I,V,X,L,C,DandM.

SymbolValueI            1V            5X            10L            50C            100D            500M            1000

For example, two is written asIIin Roman numeral, just two one's added together. Twelve is written as,XII, which is simplyX+II. The number twenty seven is written asXXVII, which isXX+V+II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is notIIII. Instead, the number four is written asIV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asIX. There are six instances where subtraction is used:

Ican be placed beforeV(5) andX(10) to make 4 and 9.

Xcan be placed beforeL(50) andC(100) to make 40 and 90.

Ccan be placed beforeD(500) andM(1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input:3Output:"III"

Example 2:

Input:4Output:"IV"

Example 3:

Input:9Output:"IX"

Example 4:

Input:58Output:"LVIII"Explanation:L = 50, V = 5, III = 3.

Example 5:

Input:1994Output:"MCMXCIV"Explanation:M = 1000, CM = 900, XC = 90 and IV = 4.

分析:因为我比较小白,所以用了一种比较暴力的方法:

在转换过程中,我用一个字典存储了所有不规则的转换规律,注意我的‘规则’仅仅是指阿拉伯数字里每增加1,在罗马数字后面追加‘I’。

通过将数字的每一位拆解开,再按照字典里的定义一一对应,可以完成转换数字的任务。

实现代码:

class Solution(object):

    def intToRoman(self, num):

        """

        :type num: int

        :rtype: str

        """

        dict = {

            1: 'I',

            4: 'IV',

            5: 'V',

            9: 'IX',

            10: 'X',

            40: 'XL',

            50: 'L',

            90: 'XC',

            100: 'C',

            400: 'CD',

            500: 'D',

            900: 'CM',

            1000: 'M'

        }

        result = ''

        num_str = str(num) # 转化为字符串形式比较好按位分割

        count = len(num_str) - 1 # 通过count确定是个十百千位

        for digit_one in num_str: #从最高位开始,如298,现在的digit_one=2

            digit_one = int(digit_one)

            digit = int(digit_one) * (10 ** count) # digit是还原过后的,digit=200

            if digit in dict.keys(): # 在字典中搜索两百没找到,于是进入elif

                result += dict[digit]

            elif digit_one < 5: # 追加l

                result += digit_one * dict[10 ** count]

            else:

                result = result + dict[5*(10**count)] + (digit_one-5) * dict[10 ** count] # 该位数字大于五的追加规则

            count -= 1 # 进入低一位

        return result

ps:最后放一个我看到别人写的比我简洁得多的代码,供自己学习

https://www.cnblogs.com/zuoyuan/p/3779581.html

相关文章

网友评论

      本文标题:【Leetcode刷题】12. Integer to Roman

      本文链接:https://www.haomeiwen.com/subject/tensmqtx.html