Integer To Roman Number
我在网上看到这个未完成的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class py_solution: def int_to_Roman(self, num): val = [ 1000, 900, 500, 400, ?????, ????, ? ] syb = [ "M","CM","D","CD", "C","XC","L","XL", "X","IX","V","IV", "I" ] roman_num = ? i = ? while ???: for _ in range(???): roman_num += ??? num -= ??? i += ??? return ??? |
我对如何解决这个问题很好奇。(我刚接触过python,这不是我的家庭作业)
1 2 3 4 5 6 7 8 9 | def int_to_Roman(num): val = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) syb = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') roman_num ="" for i in range(len(val)): count = int(num / val[i]) roman_num += syb[i] * count num -= val[i] * count return roman_num |
因此,创建val和syb,用于将int值映射到罗马值。之后,您将一个接一个地获取int值,并检查这些值中有多少适合您的输入值,然后将罗马数字的数量添加到结果中,然后从输入中删除附加值,并重复该过程,直到您达到零。