2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【python3】10進数を2進数に変換する

Posted at

はじめに

10進数を2進数に変換し、1の個数を数えるプログラムを実装しました。

問題

与えられた 10 進数の整数 N を 2 進数に変換したときの 1 の個数を答えて下さい。

実装したソースコード

実装したソースコードは以下です。

num = int(input())
flag1 = 0
syo = num
ans = ""
one_count = 0
while flag1 == 0:
    amari = int(syo % 2)
    syo = int(syo / 2)

    ans = ans + str(amari)

    if syo == 0:
        flag1 = 1

leng1 = len(ans)

for i in range(0,leng1):
    data = ans[i]
    if data== "1":
        one_count += 1
print(one_count)

こうした方が楽だと考えたソースコード

N = int(input())

binaryNumber = list()
while N // 2 > 0:
    binaryNumber.append(N % 2)
    N //= 2
binaryNumber.append(N)
reversed(binaryNumber)  # 逆順にする

ans = 0
for i in range(len(binaryNumber)):
    if binaryNumber[i] == 1:
        ans += 1
print(ans)

最後に

色々な手法をこれからも取り上げます

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?