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?

【電脳少女プログラミング2088 ─壊レタ君を再構築─】Python初心者がやってみた(廃マンションの一室編)

Posted at

はじめに

前回の記事で「自然の残る公園」をクリアして、今回は「廃マンションの一室」をクリアしたので書こうと思います。

難しくてまだクリアできてない方などに参考にしてもらえると嬉しいです。

【問題】

image.png
image.png

解答

今回もPython3を選択して書いてみました。

解答
# coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!

N = int(input()) # 整数として受け取る

digits = [] # リストをリセット

while N != 0:
    remainder = N % 3  # 余りを取得
    N = N // 3  # 商を更
    
    # 余りが2の場合は-1とし、次の桁に+1を繰り上げる
    if remainder == 2:
        digits.append(2)
        N += 1  # 繰り上げ
    else:
        digits.append(remainder)

print("".join(map(str, digits[::-1]))) # リストの順番を逆にして、文字列に変換

コード解説

上のコードの解説をすると

N = int(input())

digits = []

Nに受け取った値を整数として代入。
digitsリストをリセット


while N != 0:
    remainder = N % 3
    N = N // 3

    if remainder == 2:
        digits.append(2)
        N += 1
    else:
        digits.append(remainder)

while文でNが0になるまで下を繰り返す。

  1. remainderNを3で割ったあまりを代入
  2. NNを3で割った商を代入
  3. もしremainderが2だった場合、リストdigitsに2を追加して、Nに1足す
    remainderが2ではない場合はリストdigitsremainderを代入

6行目
print("".join(map(str, digits[::-1])))

リストdigitsを逆順([::-1])にしてから、文字列に変換(map(str, ...))し、最後にjoin()を使って一つの文字列に結合して出力


こんな感じのコードで問題を解くことができました。

最後に

記事を最後までお読みいただきありがとうございます!
今回はわからなすぎてAIの力も借りて解きました。今後解けるか怪しくなってきた( ˘•ω•˘ )

ではまた他の記事で会いましょう!またねーヾ(´∀`)ノ

参考にさせていただいたサイト

https://www.seplus.jp/dokushuzemi/ec/fe/fenavi/kind_basic_theory/decimal-and-binary-numbers/

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?