Roman to Integer

本文介绍了一种将罗马数字字符串转换为整数的方法。通过C++及Python实现,利用哈希表存储罗马数字对应的整数值,并从后往前遍历字符串进行累加。当遇到较小的数字位于较大数字前时,则从累加值中减去该小数字。

c++

class Solution {
public:
    int romanToInt(string s) {
        if (s.empty()) return 0;
        unordered_map<char, int> dict = { { 'I' , 1 },{ 'V' , 5 },
        { 'X' , 10 },{ 'L' , 50 },{ 'C' , 100 },{ 'D' , 500 },{ 'M' , 1000 } };
        int cum = dict[s.back()];
        for (int i = s.size() - 2; i >= 0; --i) {
            if (dict[s[i]] < dict[s[i + 1]])
                cum -= dict[s[i]];
            else
                cum += dict[s[i]];
        }
        return cum;
    }
};

python

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s: return 0
        dict = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
        s = list(s)
        cum = dict[s[-1]]
        for i in xrange(len(s)-2,-1,-1):
            if dict[s[i]] < dict[s[i+1]]:
                cum -= dict[s[i]]
            else:
                cum += dict[s[i]]

        return cum

reference:
https://leetcode.com/discuss/22867/clean-o-n-c-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值