大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
For example, 2
is written as II
in Roman numeral, just two one's added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed before V
(5) and X
(10) to make 4 and 9.X
can be placed before L
(50) and C
(100) to make 40 and 90.C
can be placed before D
(500) and M
(1000) to make 400 and 900.Given an integer, convert it to a roman numeral.
Input: num = 3
Output: "III"
Input: num = 4
Output: "IV"
Input: num = 9
Output: "IX"
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
1 <= num <= 3999
首先先简单的翻译一下题目
给你十进位的数字转成罗马数字表示,然後I
可以放在V
跟X
的前面,X
可以放在L
跟C
的前面,而C
可以放在D
跟M
的前面。
像是:IV,V代表的是5,I代表的是1,IV则代表的是4 (5-1),以此类推。
作法大致上是这样
IV
、IX
、XL
、XC
、CD
、CM
在计算上有点麻烦,所以我就乾脆把他们一起建在dictionary中。keys()
是为了要抓到dictionary中最大的数,用来除读进来的十进位数,再用商来判断拿来除的罗马数字应该要有几个,余数再拿来除下一轮的dictionary的数。class Solution:
def intToRoman(self, num: int) -> str:
Symbol_dict = {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'}
roman = ""
index = -1
keys = list(Symbol_dict.keys())
while num != 0:
if num // keys[index] == 0:
if num % keys[index] == 0:
roman = Symbol_dict[keys[index]]
return roman
else:
num %= keys[index]
index -= 1
else:
for times in range(num//keys[index]):
roman += Symbol_dict[keys[index]]
num %= keys[index]
index -= 1
return roman
Python
大家明天见
<<: [Day19] Vue 3 单元测试 (Unit Testing) - Event Handling
平衡灯 ( 旋转感测 ) 教学原文参考:平衡灯 ( 旋转感测 ) 这篇文章会介绍如何使用「旋转感测值...
微软Teams的新功能已经发布的: 开启新的会议体验,就是新会议与通话会在不同视窗开启,可以开起一个...
前言 透过系列文章的铺陈,我们可以再跨一步来思考远距工作了,作为一种团队协作思维的转变,为生活与工作...
Ingress Service是给予User透过特定的Port来访问Pod,当有多个Service连...
前两天教的好多好多种运算子,这些都是很常会用到的,一定要记好!!什麽?你忘记了!?这怎麽行,给你连结...