[프로그래머스](python) 3진법 뒤집기 - 월간 코드 챌린지 시즌1

berry ·2021년 7월 6일
0

Algorithm

목록 보기
49/77
post-thumbnail

문제


🧩 수도 코드

n을 3진법으로 만들고 n을 몫이 0이상일 때까지 3으로 나누어 나머지와 마지막 몫 저장
다시 10진법으로 변환하여 출력


🏁 내 풀이

def solution(n):
    num = ''
    answer = 0
    while n > 0:
        n, mod = divmod(n, 3)
        num += str(mod)
    for idx, i in enumerate(num):
        answer += int(i) * (3 ** (len(num) - (idx + 1)))
    return answer
  • while문 안에서 n(몫)>0 일 때까지 나머지 저장


🤖 error

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

문자열에 숫자를 더해서 나오는 오류 ('int' and 'str')

answer += int(i) * (3 ** (len(num) - (idx + 1)))
i 를 int(i) 로 바꾸어 해결했다.


📌 divmod()


🧩 다른 풀이

def solution(n):
    tmp = ''
    while n:
        tmp += str(n % 3)
        n = n // 3

    answer = int(tmp, 3)
    return answer
  • while n:
  • answer = int(tmp, 3)
    3진법을 10진법으로 바꿈

profile
Engineer

0개의 댓글