Decimal to binary algorithm Is there a better way to code this specific algorithm using successively division through 2 which converts decimal numbers into binary numbers without calling a built-in function?

print "Please enter a decimal number."
prompt = '&gt;&gt; '
dec_number = input(prompt)
dec_new = dec_number 
binstr = ''

'''dec2bin'''
while dec_new != 0:
  binstr += str(dec_new % 2)
  dec_new = dec_new // 2

print binstr[::-1]
In general, your idea is not bad.

The best solution, as far as I read, would be the algorithm Divide by 2 that uses a stack to keep track of the digits for the binary result.

As an intro, this algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder. 



The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence.

That said, we have:

from pythonds.basic.stack import Stack

def divideBy2(decNumber):
    remstack = Stack()

    while decNumber &gt; 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString

print(divideBy2(42))


Comments regarding your code:


Why did you do this: dec_new = dec_number ? You could've just use dec_number. There's no need of assigning its value to another variable.
This: dec_new = dec_new // 2 could be as well as the above line of your code rewritten as: dec_new //= 2
The indentation should contain 4 spaces, not 2.


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 &gt; 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 and 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 &gt; 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")
&gt;&gt; 00111110