您的位置:首页 > 编程语言 > Python开发

【python】【leetcode】【算法题目12—Integer to Roman】

2016-12-04 13:14 323 查看
一、题目描述

题目原文:

Given an integer, convert it to a roman numeral.

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

(给出数字1~3999中的一个数字,把它转化为罗马数字输出)

二、题目分析

思路:建立一个字典,将1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000,2000,3000对应的

罗马数字以键值对的形式存放在字典里。将输入的数字逐位(从个位到千位)加权(个位*1,十位*10,百位*100,千位*1000)计算后,

依次从字典中取出对应的罗马数字以字符串的形式累加在一起输出即可。

三、Python代码

class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
value_dic = {1 : 'I', 2 : 'II', 3 : 'III', 4 : 'IV', 5 : 'V', 6 : 'VI', 7 : 'VII', 8 : 'VIII', 9 : 'IX',
10 : 'X', 20 : 'XX', 30 : 'XXX', 40 : 'XL', 50 : 'L', 60 : 'LX',  70 : 'LXX', 80 : 'LXXX', 90 : 'XC',
100 : 'C', 200 : 'CC', 300 : 'CCC', 400 : 'CD', 500 : 'D', 600 : 'DC', 700 : 'DCC', 800 : 'DCCC', 900 : 'CM',
1000 : 'M', 2000 : 'MM', 3000 : 'MMM'}
numplace = []
count = 0
while num > 0:
temp = num % 10
if temp != 0 :
numplace.append(temp * 10 ** count)
num = num / 10
count += 1
numplace.reverse()
result = []
for i in range(0, len(numplace)):
result.append(value_dic[numplace[i]])
result = ''.join(result)
return result


四、其他

题目链接:https://leetcode.com/problems/integer-to-roman/

Runtime: 130 ms

想法不够优化,欢迎大家留言交流~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息