当前位置:网站首页>【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,喜欢的可以点个收藏和关注,我们下次再见!
边栏推荐
- PWM breathing lamp
- Take you ten days to easily complete the go micro service series (I)
- LeetCode 4. Find the median (hard) of two positive arrays
- What will you do after digital IC Verification?
- js删除字符串中的子串
- 大厂面试总结大全
- AcWing 300. Task arrangement
- 远程办公对我们的各方面影响心得 | 社区征文
- A week of short video platform 30W exposure, small magic push helps physical businesses turn losses into profits
- Day 18 of leetcode dynamic planning introduction
猜你喜欢

大厂面试总结大全

LeetCode 2. Add two numbers

你想要的宏基因组-微生物组知识全在这(2022.7)

寒门再出贵子:江西穷县考出了省状元,做对了什么?

SQL solves the problem of continuous login deformation holiday filtering

Ap和F107数据来源及处理

Easy language ABCD sort

串口控制舵机转动

What is normal distribution? What is the 28 law?
![[error record] error -32000 received from application: there are no running service protocol](/img/6c/66099650de46cac88b805e6cfb90b9.jpg)
[error record] error -32000 received from application: there are no running service protocol
随机推荐
In MySQL and Oracle, the boundary and range of between and precautions when querying the date
Lampe respiratoire PWM
Multi task prompt learning: how to train a large language model?
Learning Weekly - total issue 60 - 25th week of 2022
Easy language ABCD sort
Yolov5 practice: teach object detection by hand
Executive engine module of high performance data warehouse practice based on Impala
Unity Json 编写
Yyds dry goods inventory # look up at the sky | talk about the way and principle of capturing packets on the mobile terminal and how to prevent mitm
vscode设置删除行快捷键[通俗易懂]
电脑自带软件使图片底色变为透明(抠图白底)
PCL 点云镜像变换
Global and Chinese markets for airport baggage claim conveyors 2022-2028: technology, participants, trends, market size and share Research Report
OpenPose的使用
TCP congestion control details | 2 background
John blasting appears using default input encoding: UTF-8 loaded 1 password hash (bcrypt [blowfish 32/64 x3])
PhD Debate-11 预告 | 回顾与展望神经网络的后门攻击与防御
学习周刊-总第60期-2022年第25周
A week of short video platform 30W exposure, small magic push helps physical businesses turn losses into profits
路由模式:hash和history模式