0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

12. Integer to Roman 解答例・解説

Posted at

問題内容

数字を入力したら、ローマ数字の表記に変換して出力するようにしなさいというもの。

解答例

sample
class Solution:
    def intToRoman(self, num: int) -> str:
        num_map = {
            1:"I",
            5:"V",  4:"IV",
            10:"X",  9:"IX",
            50:"L",  40:"XL",
            100:"C",  90:"XC",
            500:"D",  400:"CD",
            1000:"M",  900:"CM"
        }

        r = ''

        for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
            while n <= num:
                r += num_map[n]
                num -= n
        return r

解説

上のコードはmap定義の部分とrの行、そしてfor文という3つに分かれています。

例えば、3749という数字を自力でローマ数字に変換するとき、
「3は千の位だからMMM、7は百の位だから……」
というふうに考えると思います。

この考え方をそのままプログラムに書き起こそうとすると大変なので、
「その数字が1000以上であれば千の位に数字がある」
というように考えるところがこの問題のポイントです。

それぞれのローマ数字に対応する数字が比較をする際に必要なため、mapで整理しています。

r += num_map[n]
num -= n

そして条件に合致すれば出力の文字列に追加し、入力された数字から引いてしまえば重複なく更新することができます。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?