当前位置:网站首页>【Leetcode】13. 罗马数字转整数
【Leetcode】13. 罗马数字转整数
2022-07-02 14:18:00 【wangzirui32】
博文作者 wangzirui32
喜欢的可以 点赞 收藏 关注哦~~
本文首发于CSDN,未经许可禁止转载
1. 题目描述
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/roman-to-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题思路
我们可以创建一个字典,将每单个罗马数字与阿拉伯数字作为键值对,构成罗马数字表,然后使用for
循环键值对(k
和v
),检测字符串s
中存在几个k
, 有一个k
就有一个v
,可以使用乘法计算,然后去除字符串中所有k
,然后,进入下一次循环,最后返回结果。
3. 代码实现
Code:
class Solution:
def romanToInt(self, s: str) -> int:
"""罗马数字转整数"""
"""注意:这里IV,IX等特殊的罗马数字在字典的前面,这是为了避免转换错误。"""
roman_table = {
"IV": 4,
"IX": 9,
"XL": 40,
"XC": 90,
"CD": 400,
"CM": 900,
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
result = 0 # 结果
for k, v in roman_table.items(): # 遍历字典
result += s.count(k) * v # 查询k的数量 * k所代表的值(v)
s = s.replace(k, "") # 替换k 避免重复计算
return result
4. 最终结果
好了,今天的课程就到这里,我是wangzirui32,喜欢的可以点个收藏和关注,我们下次再见!
边栏推荐
- js删除字符串中的子串
- Global and Chinese markets for slotting milling machines 2022-2028: Research Report on technology, participants, trends, market size and share
- Machine learning perceptron model
- 远程办公对我们的各方面影响心得 | 社区征文
- According to the atlas of data security products and services issued by the China Academy of information technology, meichuang technology has achieved full coverage of four major sectors
- [error record] error -32000 received from application: there are no running service protocol
- Executive engine module of high performance data warehouse practice based on Impala
- LeetCode 4. 寻找两个正序数组的中位数(hard)
- Kubernetes three open interfaces first sight
- [fluent] dart data type boolean type (boolean type definition | logical operation)
猜你喜欢
上传代码到远程仓库报错error: remote origin already exists.
TCP server communication process (important)
Yolov5 practice: teach object detection by hand
LeetCode 2. Add two numbers
John blasting appears using default input encoding: UTF-8 loaded 1 password hash (bcrypt [blowfish 32/64 x3])
What if the win11 app store cannot load the page? Win11 store cannot load page
数字IC手撕代码--投票表决器
La boîte de connexion du hub de l'unit é devient trop étroite pour se connecter
A week of short video platform 30W exposure, small magic push helps physical businesses turn losses into profits
go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)
随机推荐
远程办公对我们的各方面影响心得 | 社区征文
数字IC手撕代码--投票表决器
Ap和F107数据来源及处理
PWM breathing lamp
大廠面試總結大全
System Verilog实现优先级仲裁器
LeetCode 3. Longest substring without duplicate characters
The macrogenome microbiome knowledge you want is all here (2022.7)
什么是泛型?- 泛型入门篇
ROW_ NUMBER()、RANK()、DENSE_ Rank difference
C语言中sprintf()函数的用法
串口控制舵机转动
LeetCode 5. 最长回文子串
pwm呼吸燈
大厂面试总结大全
⌈ 2022 ⌋ how to use webp gracefully in projects
618深度複盤:海爾智家的制勝方法論
【征文活动】亲爱的开发者,RT-Thread社区喊你投稿啦
[error record] the connection of the flutter device shows loading (disconnect | delete the shuttle/bin/cache/lockfile file)
[error record] error -32000 received from application: there are no running service protocol