How to convert a decimal to binary using recursion in Python

2 Answers

0 votes
def decimal_to_binary(n):
    if n > 1:
        decimal_to_binary(n//2)
    print(n % 2, end='')
 
 
decimal = 41
 
decimal_to_binary(decimal)
 
'''
run:
 
101001
 
'''

 



answered May 30, 2017 by avibootz
edited May 30, 2017 by avibootz
0 votes
def decimal_to_binary(n):
    if n < 0:
        return 'decimal < 0'
    elif n == 0:
        return '0'
    else:
        return decimal_to_binary(n//2) + str(n % 2)
 
 
decimal = 41
 
s = decimal_to_binary(decimal)
 
print(s)
 
'''
run:
 
0101001
 
'''

 



answered May 30, 2017 by avibootz

Related questions

1 answer 157 views
1 answer 131 views
1 answer 225 views
1 answer 179 views
3 answers 160 views
2 answers 149 views
1 answer 145 views
...