[LeetCode][Python]Integer to Roman

# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'
https://oj.leetcode.com/problems/integer-to-roman/
Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.
===Comments by Dabay===
先google一下罗马数字的表示:
I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000
主要问题是会有一些4,40之类的表示。
比如999的时候,因为900可以表示为CM,所以需要先生成CM,数字减少900为99;而不是减少500为499.
可以生成一个有序的键值表,每次减少最大的,直到剩下的数小于hash表中的最大数,把这个最大数删掉继续处理。
'''

class Solution:
# @return a string
def intToRoman(self, num):
pairs = [
(1000,"M"),
(900,"CM"),
(500,"D"),
(400,"CD"),
(100,"C"),
(90,"XC"),
(50,"L"),
(40,"XL"),
(10,"X"),
(9,"IX"),
(5,"V"),
(4,"IV"),
(1,"I")
]
res = ""
for (n, s) in pairs:
while num >= n:
res = res + s
num = num - n
return res


def main():
s = Solution()
print s.intToRoman(6)


if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)


转载于:https://www.cnblogs.com/Dabay/p/4231423.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值