13. Roman to Integer

54 篇文章 0 订阅
44 篇文章 0 订阅

method1: 之前的太繁琐

这样写不符合程序设计,虽然可读,但不简洁。

class Solution:
    def romanToInt(self, s: str) -> int:
        num = 0
        i = 0
        while i < len(s):
            if i < len(s) and s[i] == 'M':
                num += 1000
                i += 1
            if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'M':
                num += 900
                i += 2
            if i < len(s) and s[i] == 'D':
                num += 500
                i += 1
            if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'D':
                num += 400
                i += 2
            if i < len(s) and s[i] == 'C':
                num += 100
                i += 1
            if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'C':
                num += 90
                i += 2
            if i < len(s) and s[i] == 'L':
                num += 50
                i += 1
            if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'L':
                num += 40
                i += 2
            if i < len(s) and s[i] == 'X':
                num += 10
                i += 1
            if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'X':
                num += 9
                i += 2
            if i < len(s) and s[i] == 'V':
                num += 5
                i += 1
            if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'V':
                num += 4
                i += 2
            if i < len(s) and s[i] == 'I':
                num += 1
                i += 1
        return num

method 2: 2 pointers

prev指向curr的前一个数。
例一:IV:I 比 V 小, 那么执行if语句, 按正常循环,当遍历到 V时,结果为6,可见多加了一个 I,相当于 V + I = 6,
但是因为prev < curr,说明不对,需要修改错误,那么就应该是 6 - I * 2 = 4
例二:VI, 按照正常情况, 不经过if语句, 直接输出6

class Solution:
    def romanToInt(self, s: str) -> int:
        table = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
        res = 0
        prev = table['M']
        for c in s:
            curr = table[c]
            res += curr
            if prev < curr:
                res -= prev * 2
            
            prev = curr
        return res
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    const table = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    };
    let res = 0, prev = table['M'];
    for (c of s) { // not c in s
        let curr = table[c];
        res += curr;
        if (prev < curr) {
            res -= prev * 2;
        }
        prev = curr
    }
    return res
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值