[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Lv1] 3์ง„๋ฒ• ๋’ค์ง‘๊ธฐ / Python

๐Ÿ“š Problem Solving/Programmers

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - 3์ง„๋ฒ• ๋’ค์ง‘๊ธฐ

์ž์—ฐ์ˆ˜ n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. n์„ 3์ง„๋ฒ• ์ƒ์—์„œ ์•ž๋’ค๋กœ ๋’ค์ง‘์€ ํ›„, ์ด๋ฅผ ๋‹ค์‹œ 10์ง„๋ฒ•์œผ๋กœ ํ‘œํ˜„ํ•œ ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”. ์ œํ•œ์‚ฌํ•ญ n์€ 1 ์ด์ƒ 100,000,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜

programmers.co.kr

import sys

input = sys.stdin.readline

n = int(input())


def solution(n):
    temp = []
    answer = 0
    if n == 1:
        return 1
    while n > 1:
        temp.append(n % 3)
        n //= 3
        if n == 1:
            temp.append(n)
    for i in range(len(temp)):
        answer += int(temp[i]) * (3 ** (len(temp) - i - 1))
    return answer


print(solution(n))

 

ํ•ด์„ค

n์„ 3์œผ๋กœ ๋‚˜๋ˆ„๋ฉด์„œ ๋‚˜๋จธ์ง€๋ฅผ temp์— ์ €์žฅํ•˜๋ฉด ๊ตณ์ด ๋’ค์ง‘์„ ํ•„์š”๊ฐ€ ์—†๋‹ค.

 

ex)

45 -> 1200

45%3 = 0, 15%3 = 0, 5%3 = 2, 5//3 = 1 -> 0021

 

temp์˜ ๊ฐ’๋“ค๋กœ ๋‹ค์‹œ 10์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด ๋!