[LeetCode] Roman To Integer 解题报告

本文介绍了一种将罗马数字转换为整数的有效算法。通过扫描输入的罗马数字字符串,利用字符映射表来确定每个字符对应的数值,并根据特定规则进行累加或差分运算,最终得到整数结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

» Solve this problem

[解题思路]

从前往后扫描,用一个临时变量记录分段数字。
  • 如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如IV = 5 – 1
  • 否则,将当前值加入到结果中,然后开始下一段记录。比如VI = 5 + 1, II=1+1

[Code]

1:    inline int c2n(char c) {  
2: switch(c) {
3: case 'I': return 1;
4: case 'V': return 5;
5: case 'X': return 10;
6: case 'L': return 50;
7: case 'C': return 100;
8: case 'D': return 500;
9: case 'M': return 1000;
10: default: return 0;
11: }
12: }
13: int romanToInt(string s) {
14: // Start typing your C/C++ solution below
15: // DO NOT write int main() function
16: int result=0;
17: for(int i =0; i< s.size(); i++)
18: {
19: if(i>0&& c2n(s[i]) > c2n(s[i-1]))
20: {
21: result +=(c2n(s[i]) - 2*c2n(s[i-1]));
22: }
23: else
24: {
25: result += c2n(s[i]);
26: }
27: }
28: return result;
29: }

关联题:
http://codingtmd.azurewebsites.net/leetcode-integer-to-roman-%e8%a7%a3%e9%a2%98%e6%8a%a5%e5%91%8a/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值