#419 Roman to Integer

本文介绍了一种将罗马数字转换为整数的有效算法。通过分析罗马数字的构成特点,文章提供了一个C++实现示例,该算法能够正确处理1到3999范围内的罗马数字,并详细解释了其工作原理。

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

题目描述:

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

Example

IV -> 4

XII -> 12

XXI -> 21

XCIX -> 99

题目思路:

这题需要知道单个roman到int的mapping。知道之后,发现roman number也是从个位数开始看的,看的时候顺带看前一位。如果前一位比当前位的数字小,就意味着减法(当前位-前一位);否则,就是正常的数字相加。

Mycode(AC = 18ms):

class Solution {
public:
    /**
     * @param s Roman representation
     * @return an integer
     */
    int romanToInt(string& s) {
        // Write your code here
        int ans = 0;
        
        // starting from tail of s:
        // 1. if s[i - 1] <= s[i], then it means number = s[i] - s[i - 1]
        // 2. if i == 0, last one doesn't need check item 1).
        // 3. else, then add the current roman number
        for (int i = s.length() - 1; i >= 0; i--) {
            if (i == 0) {
                ans += r2int(s[i]);
            }
            else {
                if (r2int(s[i]) > r2int(s[i - 1])) {
                    ans += r2int(s[i]) - r2int(s[i - 1]);
                    i--;
                }
                else {
                    ans += r2int(s[i]);
                }
            }
        }
        
        return ans;
    }
    
    // mapping between single roman to int
    int r2int(char ch) {
        if (ch == 'I') {
            return 1;
        }
        else if (ch == 'V') {
            return 5;
        }
        else if (ch == 'X') {
            return 10;
        }
        else if (ch == 'L') {
            return 50;
        }
        else if (ch == 'C') {
            return 100;
        }
        else if (ch == 'D') {
            return 500;
        }
        else if (ch == 'M') {
            return 1000;
        }
        else {
            return 0;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值