您的位置:首页 > 其它

12 leetcode - Integer to Roman

2016-11-16 14:11 260 查看
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Integer to Roman,Input is guaranteed to be within the range from 1 to 3999.
中文:整数变为罗马数字,范围1~3999
'''
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
a = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
"M", "MM", "MMM"]
b = range(1,10) + range(10,100,10) + range(100,1000,100) + [1000,2000,3000]
d = dict(zip(b,a))
ret = []
times = 1
while num:
cnt = (num %10)*times
if d.has_key(cnt):
ret.append(d[cnt])
num /= 10
times *= 10
return ''.join(reversed(ret))

if __name__ == "__main__":
s = Solution()
print s.intToRoman(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息