1
0

More than 3 years have passed since last update.

【Python】10進数を2進数に変えるプログラムを作ってみた!

Last updated at Posted at 2021-09-09

 Pythonを学び始めたので、とりあえずできそうなプログラムを手当たり次第作っています。今回は10進数を2進数に変えるプログラムを原始的に作ってみました。

def base_number(num):
    remainders = []
    while True:
        remainder = num % 2
        remainders.append(str(remainder))
        num //= 2
        if num == 0:
            remainders.reverse()
            binary = "".join(remainders)
            print("2進数は" + binary + "です")
            break

num = int(input("数字を入力してください:"))
base_number(num)

出力結果は以下のようになります。

数字を入力してください:160
2進数は10100000です

 もっと簡単に2進数を出せる数学の公式があれば、より簡潔なコードが書けると思いますし、Pythonにも2進数を簡単に出しやすいメソッドがあるかもしれませんが、アルゴリズムを考える勉強のため、まずは自分なりに考えてみました。
 結果的に「reverse」や「join」といったメソッドを使ってしまったため、これを使わない方法も考えてみたいと思います。
 またこの2進数の値をInteger型にしようとすると、「00000101」のような場合は「101」になってしまいますし、String型で仕方ないのかなと思っています。

 ご意見いただけると勉強になります。


1
0
12

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