I want to use recursion in converting a decimal number into octal. I have a problem in keeping track of the results of each recursion step and append them into a list or a string. I will appreciate your help.
def dectoOct(decimal):
L = ''
if decimal == 0:
return 0
if decimal > 0:
L = str(decimal % 8) + L
dectoOct(decimal//8)
return L
print(dectoOct(30))
>Solution :
You just need to return the value as you go:
def dec_to_oct(n):
if n == 0:
return '0'
left = n // 8
if left:
return dec_to_oct(n // 8) + str(n % 8)
else:
return str(n % 8)
# all are strings
foo(0) # 0
foo(37) # 45
foo(40) # 50