整数转罗马数字 python
生活随笔
收集整理的這篇文章主要介紹了
整数转罗马数字 python
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原文鏈接
一個(gè)容易理解的方法
class Solution(object):def intToRoman(self, num):""":type num: int:rtype: str"""tmp = []roman = ''if not num:raise ValueErrorwhile num >= 1000:num -= 1000tmp.append('M')while num >= 900:num -= 900tmp.append('CM')while num >= 500:num -= 500tmp.append('D')while num >= 400:num -= 400tmp.append('CD')while num >= 100:num -= 100tmp.append('C')while num >= 90:num -= 90tmp.append('XC')while num >= 50:num -= 50tmp.append('L')while num >= 40:num -= 40tmp.append('XL')while num >= 10:num -= 10tmp.append('X')while num >= 9:num -= 9tmp.append('IX')while num >= 5:num -= 5tmp.append('V')while num >= 4:num -= 4tmp.append('IV')while num >= 1:num -= 1tmp.append('I')return roman.join(tmp) class Solution(object):def intToRoman(self, num):""":type num: int:rtype: str"""tmp = []hashmap = {'I': 1, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900, 'V': 5,'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}sort_hashmap = sorted(hashmap.items(), key=lambda _: _[1], reverse=True)roman = ''for i in range(len(sort_hashmap)):while num>=sort_hashmap[i][1]:num -= sort_hashmap[i][1]tmp.append(sort_hashmap[i][0])return roman.join(tmp)總結(jié)
以上是生活随笔為你收集整理的整数转罗马数字 python的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode-寻找两个正序数组的中位
- 下一篇: python 字符串join