如何获取罗马数字字符串并将其转换为base10数字? [英] How to take a Roman Numeral String and convert it to base10 digit?

查看:464
本文介绍了如何获取罗马数字字符串并将其转换为base10数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在构建一个采用罗马数字并将其转换为基数为10的示例项目。我尝试让这个工作,但没有完成我的目标。有谁知道怎么做到这一点?我正在添加下面的10个罗马数字作为参考。谢谢!

So I am building a sample project which takes roman numerals and converts it to a base10 digit. I tried getting this to work but have not accomplished my goal. Is there anyone who knows how to accomplish this? I am adding the roman numerals up to 10 below for reference. Thanks!

1 - I
2 - II
3 - III
4 - IV
5 - V
6 - VI
7 - VII
8 - VIII
9 - IX
10 - X

1 - I 2 - II 3 - III 4 - IV 5 - V 6 - VI 7 - VII 8 - VIII 9 - IX 10 - X

推荐答案

您只需要以相反的方式迭代罗马字符串字符并映射这些字符值。从maxValue等于零开始,切换字母值,将其保存为maxValue,如果值等于maxValue,则添加它,否则减去实际值。您也可以使用正则表达式(严格或not)验证并在失败时抛出错误。试试这样:

All you need is to iterate through your roman string characters in a reverse way and map those characters values. Start with maxValue equal to zero, switch the letters value, save it as the maxValue and if the value is equal to maxValue add it otherwise subtract the actual value. You can also use regex (strict or not) to validate and throw an error in case it fails. Try like this:

Xcode 9.x•Swift 4.x

注意:对于 Swift 3 版本或更早版本,请检查编辑记录。

Note: for Swift 3 version or earlier check the edit history.

extension String {
    enum RomanParsingError: Error {
        case invalidNumber
    }
    func romanNumeralValue() throws -> Int  {
        guard range(of: "^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$", options: .regularExpression) != nil else {
            throw RomanParsingError.invalidNumber
        }
        var result = 0
        var maxValue = 0
        uppercased().reversed().forEach {
            let value: Int
            switch $0 {
            case "M":
                value = 1000
            case "D":
                value = 500
            case "C":
                value = 100
            case "L":
                value = 50
            case "X":
                value = 10
            case "V":
                value = 5
            case "I":
                value = 1
            default:
                value = 0
            }
            maxValue = max(value, maxValue)
            result += value == maxValue ? value : -value
        }
        return result
    }
}

用法:

do {
    let decimal = try "MCMLXXVIII".romanNumeralValue()
    print(decimal)   // 1978
} catch {
    print(error)
}


do {
    let decimal = try "IIIV".romanNumeralValue()
    print(decimal)
} catch {
    print(error)   // "invalidNumber\n"
}

这篇关于如何获取罗马数字字符串并将其转换为base10数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆