LoginSignup
7
3

More than 5 years have passed since last update.

面接で絶対に押さえておきたいアルゴリズム問題(4)

Last updated at Posted at 2017-06-28

問題:Roman to Int (ローマ字から整数へ)

(0~4999)までのローマ字を数字に変換せよ。ちなみにローマ数字と整数は以下。

let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

例:

input: DCXXI
return: 621

input: MCMXCVI
return: 1996

input MMMMXCVI
return: 4096

ヒント:

解答:

func romanToInt(_ s: String) -> Int {

        var arabicValue = 0
        var romanValue = s

        let romanChars:[String] = ["CM", "M", "CD", "D", "XC", "C", "XL", "L", "IX", "X", "IV", "V", "I"]
        let arabicValues = [900, 1000, 400, 500, 90, 100, 40, 50, 9, 10, 4, 5, 1]


        for (index, chars) in romanChars.enumerated(){


            if romanValue.range(of: chars) != nil{

                let tok = romanValue.components(separatedBy: chars)
                let count = tok.count-1

                arabicValue += (arabicValues[index] * (count))

                romanValue = romanValue.replacingOccurrences(of: chars, with: "")
            }

        }

    return arabicValue

 }

メモ / ポイント

  1. まずは2文字を探して、1文字ずつのローマ字を探す
  2. それぞれ見つけたら、数字を足していき、ローマ文字を取っていく。
  3. ポイント:2文字のローマ字から先に探す

あくまで、自分流解き方です!
もっといい方法があれば、どしどし載せて言ってください。

メモ / ポイント

ちなみに、「数字 > ローマ字」を解いた人がいたので、参考にしてみました
https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7

7
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3