0
Can anyone please try to break down this code for me. It converts a decimal to binary. I don't understand how the code does that
4 Respostas
+ 1
This is kind of the way I understand it.
x= int(input())
def convert(num):
if num== 0:
return 0
else:
bin_val = num % 2 + 10 * convert(num // 2)
return (bin_val)
print(convert(x))
using a value of 4
order in stack ->FILO First in last out
bin_val = (1%2 + 10 % (0 is returned) need to rerun convert with value of 1//2 which = 0
----> After 0 is returned
----> you have ((1%2)=1) + ((10 * 0)=0) -> return 1
bin_val = (2%2 + 10 % (yet unknown)) need to rerun convert with value of 2//2 which = 1
----> After 0 is returned again
----> you have ((2%2)=0) + ((10 * 0)=0 -> return 0
bin_val = (4%2 + 10 % (yet unknown)) need to rerun convert with value of 4//2 which = 2
----> After 0 is returned again
----> you have ((4%2)=0) + ((10 * 0)=0 -> return 0
So all together I have 100
using a value of 5
order in stack
bin_val = (1%2 + 10 % (0 is returned) need to rerun convert with value of 1//2 which = 0
----> After 0 is returned
----> you have ((1%2)=1) + ((10 * 0)=0) -> return 1
bin_val = (2%2 + 10 % (yet unknown)) need to rerun convert with value of 2//2 which = 1
----> After 0 is returned again
----> you have ((2%2)=0) + ((10 * 0)=0 -> return 0
bin_val = (5%2 + 10 % (yet unknown)) need to rerun convert with value of 5//2 which = 2
----> After 0 is returned again
----> you have ((5%2)=1) + ((10 * 0)=0 -> return 1
So all together I have 101
using a value of 6
order in stack
bin_val = (1%2 + 10 % (0 is returned) need to rerun convert with value of 1//2 which = 0
----> After 0 is returned
----> you have ((1%2)=1) + ((10 * 0)=0) -> return 1
bin_val = (3%2 + 10 % (yet unknown)) need to rerun convert with value of 3//2 which = 1
----> After 0 is returned again
----> you have ((3%2)=1) + ((10 * 0)=0 -> return 1
bin_val = (6%2 + 10 % (yet unknown)) need to rerun convert with value of 6//2 which = 3
----> After 0 is returned again
----> you have ((6%2)=0) + ((10 * 0)=0 -> return 0
So all together I have 110
0
To convert integers to binary you keep dividing by 2 until you reach 0.
0
Yeah, I understand that. But the whole calculation setup doesn't seem right to me.
0
Correct me if I'm wrong but doesn't always end up going to zero, thus covering to binary?
7//2 = 6//2 = 3//2 = 1//2 = 0 or 4//2 = 2//2 = 1//2 = 0