LeetCode 13. Roman to Integer

本文详细介绍了一种将罗马数字转换为整数的算法。文章首先解释了罗马数字的书写规则,尤其是减法规则,例如IV表示4。然后提供了一个C++代码实现,通过遍历字符串并比较相邻字符的值来确定是否应用减法规则。

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

13. Roman to Integer

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:
这里唯一需要注意的是:

IV  4          = V-I = 5-1 = 4
IX   9         = X-I = 10-1 = 9
XL  40		   = L-X = 50-10 = 40
XC   90 	   = C-X = 100-10 = 90
CD   400	   = D-C = 500-100 = 400
CM   900	   = X-I = 1000-100 = 900

这几个都有一个规律:第一个字母代表的值小于第二个字母代表的值。
题目给出的罗马数字一定是从大到小(字母代表的值)(最上面的英语)。所以可以发现:只要前面的字母的值小于下一个字母的值。那么就是特殊情况。

而且值等于后面一个字母的值减去前一个字母的值。



Code:

class Solution {
public:
    int romanToInt(string s) {
        const map<char,int> roman{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        int sum=0;
        auto it = s.cbegin();
        while(it != s.cend()){
            if( (it+1 !=s.cend()) && roman.at(*it) < roman.at(*(it+1))){
                sum+=roman.at(*(it+1))-roman.at(*it);
                it+=2;
            }
            else{
                sum+=roman.at(*it);
                it++;
            }
        }
        return sum;
    } 
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值