[백준] 2089번 -2진수

거북이·2023년 1월 21일
0

백준[실버3]

목록 보기
38/92
post-thumbnail

💡문제접근

  • 2진수와 접근 방법을 동일하게 생각했다. 절댓값을 이용해서 해결할 수 있었다.
  • -13 = -2 × 7 + 1
  • 7 = -2 × (-3) + 1
  • -3 = -2 × 2 + 1
  • 2 = -2 × (-1) + 0
  • -1 = -2 × 1 + 1
  • 1 = -2 × 0 + 1

따라서, -13을 -2진수로 변환하면 110111이 된다.

💡코드(메모리 : 30616KB, 시간 : 36ms)

import sys

n = int(input())
result = ""
if n == 0:
    print(0)
    sys.exit()

while True:
    if n == 0:
        break
    else:
        if n < 0:
            temp = abs(n)
            if temp % 2 != 0:
                n = (abs(temp) // 2) + 1
                result += str((n * 2) - temp)
            else:
                n = (abs(temp) // 2)
                result += str((n * 2) - temp)
        elif n > 0:
            temp = n
            n = -(temp // 2)
            result += str((temp % 2))
print(result[::-1])

💡소요시간 : 10m

0개의 댓글