Part5.1_완전탐색(백트래킹,상태트리와CUT EDGE)-DFS(깊이우선탐색)기초_재귀함수를 이용한 이진수 출력

Eugenius1st·2022년 1월 20일
0

Python_algorithm

목록 보기
29/83

재귀함수를 이용한 이진수 출력

내가 생각한 코드

import sys
sys.stdin = open("input.txt", "rt")

def ch(x):
    tmp = x % 2
    res = 0
    if x==1:
        res.append(tmp)
        return res
    elif x==0:
        res.append(tmp)
        return res
    else:
        res.append(tmp)
        ch(x//2)

n = int(input())
res = []
ch(n)
for x in res[::-1]:
    print(x,end="")


그런데.. 리스트 없이 print 할 수 있지도 않나?

def ch(x):
    tmp = x % 2
    if x > 0:
        ch(x//2)
        print(tmp,end="")
    else:
        return 0

if __name__ == "__main__":
    n = int(input())
    ch(n)   

줄여보았다 리스트 없이..
근데 return 0 되어되 되나 ? ㅎㅎ

선생님 코드

import sys
sys.stdin = open("input.txt", "rt")

def DFS(x):
    if x == 0:
        return # 그냥 함수를 종료해라 !!
    else:
        DFS(x//2)
        print(x%2, end='')


if __name__ == "__main__":
    n = int(input())
    DFS(n)   

선생님은 tmp 변수도 안두셨고, return 으로만 함수를 종료하셨다... 후 오늘도 배웠다 !!!

profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글