原始題目:
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.
分析:因為我比較小白撤卢,所以用了一種比較暴力的方法:
在轉換過程中,我用一個字典存儲了所有不規(guī)則的轉換規(guī)律,注意我的‘規(guī)則’僅僅是指阿拉伯數(shù)字里每增加1,在羅馬數(shù)字后面追加‘I’。
通過將數(shù)字的每一位拆解開熙涤,再按照字典里的定義一一對應,可以完成轉換數(shù)字的任務。
實現(xiàn)代碼:
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忍抽,現(xiàn)在的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] # 該位數(shù)字大于五的追加規(guī)則
? ? ? ? ? ? count -= 1 # 進入低一位
? ? ? ? return result
ps:最后放一個我看到別人寫的比我簡潔得多的代碼鸠项,供自己學習
https://www.cnblogs.com/zuoyuan/p/3779581.html