闯关leetcode——13. Roman to Integer

题目

地址

https://leetcode.com/problems/roman-to-integer/description/

内容

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 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 before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.
  • Given a roman numeral, convert it to an integer.

Example 1:

Input: s = “III”
Output: 3
Explanation: III = 3.

Example 2:

Input: s = “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

  • 1 <= s.length <= 15
  • s contains only the characters (‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’).
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

解题

这题是要求将罗马数字转换成整型数字。这就要熟悉罗马数字特点:

  • 罗马数字通过较小的数字在较大的数字的左侧还是右侧,来决定较小的数字是进行加法操作还是减法操作。如果较小数字出现在较大数字左侧,则表示减去较小数字。比如IV,V表示5,I表示1,I小于V且出现在V的左侧,则IV表示5-1=4;如果较小的数字出现在较大数字的右侧,则表示加上较大的数字。比如VI,I出现在V的右侧,于是VI表示5+1=4。
  • 在表示一个比较大的数字时,大的数字在左侧。比如1994(MCMXCIV),表示千位的M会最先出现,表示4的IV最后出现。

基于上述规律,我们可以得出结论:如果一个数比上个数字小,则减去该数;如果大于等于上个数字,则加上该数。最后一位一定是加上。

#include <string>
#include <unordered_map>
using namespace std;

class Solution {
public:
    int romanToInt(string s) {
        const unordered_map<char, int> roman_map = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };

        int result = 0;
        int previous_value = 0;
        for (char c : s) {
            int current_value = roman_map.at(c);
            if (previous_value < current_value) {
                result -= previous_value;
            } else {
                result += previous_value;
            }
            previous_value = current_value;
        }
        result += previous_value;
        return result;
    }
};

代码地址

https://github.com/f304646673/leetcode/tree/main/13-Roman-to-Integer

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值