LoginSignup
0
1

More than 3 years have passed since last update.

はじめに

前回

#25

おすすめされた問題を解きます。
ABC105-C

考えたこと
まず、普通の2進数にするときの手法を考えます。これで10進数を2進数に変換します。これを-2進数版にします。変更点は、余りは自然数になるのでうまく余りを調整しないといけない点です。
-2で割りきれるときは余りが出ないのでそのままn//2します。余りが出る時は、n-1してから-2で割るとうまく計算できます。
この計算方法でappendしていくと、答えの順番が逆なのでreverseします。あとは、joinでstrにするだけです。

n = int(input())

if n == 0:
    print(0)
    quit()
base = []
while n != 1:
    if n % -2 == 0:
        base.append('0')
        n //= -2
    else:
        base.append('1')
        n -= 1
        n //= -2
base.append('1') #最後に1するのを忘れない
base.reverse()
ans = ''.join(base)
print(ans)

まとめ

楽しい。では、また

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