forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
integer-to-roman.py
32 lines (27 loc) · 894 Bytes
/
integer-to-roman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Time: O(n)
# Space: O(1)
#
# Given an integer, convert it to a roman numeral.
#
# Input is guaranteed to be within the range from 1 to 3999.
#
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", \
10: "X", 40: "XL", 50: "L", 90: "XC", \
100: "C", 400: "CD", 500: "D", 900: "CM", \
1000: "M"}
keyset, result = sorted(numeral_map.keys()), []
while num > 0:
for key in reversed(keyset):
while num / key > 0:
num -= key
result += numeral_map[key]
return "".join(result)
if __name__ == "__main__":
print Solution().intToRoman(999)
print Solution().intToRoman(3999)