forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteger_to_roman.py
52 lines (51 loc) · 1.69 KB
/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# -*- coding: utf-8 -*-
class Solution:
# @param {int} n The integer
# @return {string} Roman representation
def intToRoman(self, n):
# Write your code here
digits = []
while n > 0: # 罗马数字没有0
digits.append(n % 10)
n /= 10
ret = ''
for i in xrange(len(digits) - 1, -1, -1):
num = digits[i]
if (num > 0) and (num <= 3):
if i == 0: # 个位
ret += 'I' * num
elif i == 1: # 十位
ret += 'X' * num
elif i == 2: # 百位
ret += 'C' * num
else: # 千位
ret += 'M' * num
elif num == 4:
if i == 0: # 个位
ret += 'IV'
elif i == 1: # 十位
ret += 'XL'
else: # 百位
ret += 'CD'
elif num == 5:
if i == 0: # 个位
ret += 'V'
elif i == 1: # 十位
ret += 'L'
else: # 百位
ret += 'D'
elif (num >= 6) and (num <= 8):
if i == 0: # 个位
ret += 'V' + 'I' * (num - 5)
elif i == 1: # 十位
ret += 'L' + 'X' * (num - 5)
else: # 百位
ret += 'D' + 'C' * (num - 5)
elif num == 9:
if i == 0: # 个位
ret += 'IX'
elif i == 1: # 十位
ret += 'XC'
else: # 百位
ret += 'CM'
return ret