hye-log

[프로그래머스]124 나라의 숫자(Python) 본문

CodingTest/Programmers

[프로그래머스]124 나라의 숫자(Python)

iihye_ 2022. 8. 26. 15:33

0. 문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/12899

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 소개

1) 십진수를 1, 2, 4를 이용하여 변환

 

2. 입출력

# input
n = 15

# output
answer = 114

 

3. 코드

def solution(n):
    answer = ''
    num_dict = [4, 1, 2]                        # 0일 때 4, 1일 때 1, 2일 때 2 사용

    while n:                                    # n이 나누어질 때까지
        if n % 3:                               # n을 3으로 나누었을 때 나머지가 있으면
            answer += str(num_dict[n % 3])      # 나머지에 해당하는 dict 추가
            n //= 3                             # n을 3으로 나누기
        else:                                   # n을 3으로 나누었을 때 나머지가 없으면(0이면)
            answer += str(num_dict[0])          # 나머지에 해당하는 dict[0] 추가
            n = n // 3 - 1                      # n을 3으로 나눈 후 1 뺴기

    return answer[::-1]                         # 반대로 뒤집기

 

실행 결과

 

5. Github

https://github.com/iihye/Algorithm/blob/main/Programmers/nation_number.py

 

GitHub - iihye/Algorithm

Contribute to iihye/Algorithm development by creating an account on GitHub.

github.com

 

728x90
Comments