A version that better utilizes the memory would be:
def dec_to_bin(n):
bits = []
bits.append(str(0 if n%2 == 0 else 1))
while n > 1:
n = n // 2
bits.append(str(0 if n%2 == 0 else 1))
bits.reverse()
return ''.join(bits)
What I did:
- floor divide all the numbers by two repeatedly until we reach 1
- going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.
Other ways of doing it:
###Using recursion:
def dec_to_bin(x):
return dec_to_bin(x/2) + [x%2] if x > 1 else [x]
The above solution returns the result as a list which you can later on .join() then apply int() to it.
Another idea that came to my mind is as simple as:
u = format(62, "08b")
>> 00111110
The best solution, as far as I readas far as I read, would be an algorithm called Divide by 2 that uses a stack to keep track of the digits for the binary result.
A version that better (than your solution) utilizes the memory would be:
def dec_to_bin(n):
bits = []
bits.append(str(0 if n%2 == 0 else 1))
while n > 1:
n = n // 2
bits.append(str(0 if n%2 == 0 else 1))
bits.reverse()
return ''.join(bits)
What I did:
- floor divide all the numbers by two repeatedly until we reach 1
- going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.
Other ways of doing it:
###Using recursion:
def dec_to_bin(x):
return dec_to_bin(x/2) + [x%2] if x > 1 else [x]
The above solution returns the result as a list which you can later on .join() then apply int() to it.
Another idea that came to my mind is as simple as:
u = format(62, "08b")
>> 00111110