programmers- lv.1 (3진법 뒤집기)

이예송·2023년 7월 10일

PS

목록 보기
14/97

문제링크: 3진법 뒤집기

✍🏻 Information

content
언어python
난이도⭐️
풀이시간15분
제출횟수1
인터넷검색유무yes




🍒 My Code

def solution(n):
    answer = 0
    three = []
    a, b = n, n
    while a!=0:
        b = a%3
        a = a//3
        three.insert(0,b)
    three.reverse()
    for i in range(len(three)-1,-1,-1):
        square = len(three)-i-1
        answer+=three[i]*(3**square)
    return answer




💡 What I learned

  • 3진법으로 바꾼 수를 string으로 할지 list로 할지 고민했다. string으로 하면 아래와 같이 뒤집어줘야 하는데 list로 하면 reverse 메소드를 쓰면 되기 때문에+3진법을 10진법으로 바꿀때 곱하기 더 쉬울것이라 생각하여 list로 하였다.
	while a!=0:
        b = a%3
        a = a//3
        three=b+three
    for i in three:
        reverse = i + reverse
  • 그런데 int에 int(string, 진법)하면 10진법으로 출력해주는 기능이 있었다..
  • 그리고 뒤집어 줄 필요 없이 처음부터 뒤집어서 저장하면 됐다..
    위 둘을 합친 코드는 아래와 같다
def solution(n):
    tmp = ''
    while n:
        tmp += str(n % 3)
        n = n // 3

    answer = int(tmp, 3)
    return answer

0개의 댓글