Recursion from decimal to binary | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Recursion from decimal to binary

The task is: The given code defines a recursive function convert(), which needs to convert its argument from decimal to binary. However, the code has an error. Fix the code by adding the base case for the recursion, then take a number from user input and call the convert() function, to output the result. https://code.sololearn.com/cdo9ScG7h2v3/?ref=app Actually, my code is pretty much exactly the Sololearn solution. Why is there no output?

26th Aug 2022, 7:38 AM
Sonja
8 Answers
+ 2
After return you leave the function. Anyway...some guys prefer if else construct. It might be a bit safer.
26th Aug 2022, 1:28 PM
Oma Falk
Oma Falk - avatar
+ 2
You might want to look at it again. Outdenting line 4 seems to fix the problem (got output). Though I haven't tested it using many numbers.
26th Aug 2022, 8:59 AM
Ipang
+ 1
Only return 0 should run if num==0, the recursive step needs an else-path.
26th Aug 2022, 8:10 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
If that is their suggested solution then yes it is incorrect. Perhaps you find the time to report the error so that it can be fixed.
26th Aug 2022, 8:13 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Ani Jona 🕊 no.... else is not required. Ipang that's it. Decent line 4.
26th Aug 2022, 10:13 AM
Oma Falk
Oma Falk - avatar
+ 1
Why is the else actually not needed here?
26th Aug 2022, 1:07 PM
Sonja
0
Thanks. So the Sololearn solution is wrong here…
26th Aug 2022, 8:12 AM
Sonja
0
#If statement will add the base case. You must include the else statement, otherwise it will print None. def convert(num): if num == 0: return 0 else: return (num % 2 + 10 * convert(num // 2)) num = int(input()) print(convert(num))
29th Oct 2023, 3:00 PM
Kanake Karani
Kanake Karani - avatar