Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลงทศนิยมเป็นไบนารีด้วย Recursion ใน Python

ค่าไบนารีที่เทียบเท่าของเลขทศนิยม ได้จากการพิมพ์เศษจากการหารซ้ำๆ ด้วย 2 ในลำดับย้อนกลับ วิธีแก้ปัญหาแบบ Recursive มีดังนี้:

def tobin(x):
    strbin = ''
    if x > 1:
        tobin(x // 2)
    print(x % 2, end='')

num = int(input('enter a number: '))
tobin(num)

# ทดสอบผลลัพธ์
# enter a number 25
# 11001
# enter a number 16
# 10000