【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代码
四、其他
题目链接:https://leetcode.com/problems/integer-to-roman/
Runtime: 130 ms
想法不够优化,欢迎大家留言交流~
题目原文:
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
想法不够优化,欢迎大家留言交流~
相关文章推荐
- python写算法题:leetcode: 12. Integer to Roman
- 【python】【leetcode】【算法题目1—Two Sum】
- 【python】【leetcode】【算法题目9—Palindrome Number】
- 【算法——Python实现】快速排序的优化:三路快速排序及Leetcode题目应用
- 【python】【leetcode】【算法题目2—Add Two Numbers】
- Leetcode 12. Integer to Roman The Solution of Python
- [leetcode: Python]12. Integer to Roman
- 【python】【leetcode】【算法题目4—Median of Two Sorted Arrays】
- 【python】【leetcode】【算法题目387—First Unique Character in a String】
- 【python】【leetcode】【算法题目412—Fizz Buzz】
- LeetCode 12 Integer to Roman(C,C++,Java,Python)
- 【python】【leetcode】【算法题目6—ZigZag Conversion】
- 【python】【leetcode】【算法题目283—Palindrome Number】
- 【python】【leetcode】【算法题目383—Ransom Note】
- 【python】【leetcode】【算法题目64—Minimum Path Sum】
- LeetCode 12 — Integer to Roman(C++ Java Python)
- 【python】【leetcode】【算法题目167—Two Sum II - Input array is sorted】
- 【python】【leetcode】【算法题目389—Find the Difference】
- 【python】【leetcode】【算法题目344—Reverse String】
- 【python】【leetcode】【算法题目7—Reverse Integer】