leetcode-13-Roman to Integer
题目描述:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven 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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III" Output: 3
Example 2:
Input: "IV" Output: 4
Example 3:
Input: "IX" Output: 9
Example 4:
Input: "LVIII" Output: 58 Explanation: C = 100, L = 50, XXX = 30 and III = 3.
Example 5:
Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
要完成的函数:
int romanToInt(string s)
说明:
1、这道题给定一个字符串s,要求将字符串中的罗马数字转化为阿拉伯数字(十进制)显示出来,I/V/X/L/C/D/M分别表示1/5/10/50/100/500/1000,除此之外,还定义了两条规则,如下:
大数字在左,小数字在右,比如VI表示6。
如果小数字在左,大数字在右,那么它们的组合结果是大数字减去小数字,如IV,表示5-1=4,IX=10-1=9,CM=1000-100=900。
2、明白了题意,我们可以逐个处理字符,如果该字符比下一个字符大或者相等,那么总数加上当前字符。
如果该字符比下一个字符小,那么总数减去当前字符。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int romanToInt(string s) { int sum=0,i=0,s1=s.size(); vector< int >char2num={100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10}; //每个罗马字符减去67,作为index,得到的值就是相应的阿拉伯数字。 while (i<s1-1) //此处也可以使用map { if (char2num[s[i]-67]>=char2num[s[i+1]-67]) sum+=char2num[s[i]-67]; else sum-=char2num[s[i]-67]; i++; } sum+=char2num[s[i]-67]; //加上最后一个字符对应的阿拉伯数字 return sum; } |
上述代码实测116ms,beats 44.21% of cpp submissions。
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· 开发者新选择:用DeepSeek实现Cursor级智能编程的免费方案
· 【译】.NET 升级助手现在支持升级到集中式包管理
· 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统
· Tinyfox 发生重大改版