Instead of inserting the digits at the bottom of the list and then reversing it, why not always insert the new elements at the beginning of the list? So they’re already in the right order.
Just always use the zero index on insert
, thus:
n = # ler o número
result = []
while n > 0:
result.insert(0, n % 2) # insere sempre no início da lista
n //= 2
# depois você imprime os números como achar melhor
# um em cada linha
for i in result:
print(i)
# ou todos juntos na mesma linha
print(''.join(map(str, result)))
print(*result, sep='')
Having the numbers in the correct order makes it easy to print. You can use the for
as it was already doing, or if you want, print all on the same line, either using join
or the options of print
.
Note: you don’t need the if
/else
. In your code you did it:
if(n % 2 == 0):
cont.insert(aux,n % 2)
n = n // 2
else:
cont.insert(aux,n % 2)
n = n // 2
I mean, he did the exact same thing in if
and in the else
. If the same thing is done regardless of the condition, then eliminate the condition.
Another option (with caveats, see comments below) is to construct the value using calculations only. Ex:
n = 21
result = expoente = 0
while n > 0:
n, digito = divmod(n, 2)
result += (10 ** expoente) * digito
expoente += 1
print(result) # 10101
I used divmod
, which already returns the split result and the rest of it (is how to use //
and %
at once).
Remember that in this case I’m generating a number on base 10, the digits of which are the same as n
base 2 (in the example above, the digits 10101
equals to 21 in base 2, but the value of it is "ten thousand one hundred", so no use result
thinking he’s worth twenty-one).
Finally, this transformation is valid as an exercise, but if you only want to show the number in base 2, just do print(f'{n:b}')
, as you have suggested another answer.
Welcome to Stackoverflow! The last index of a vector is always the size of the same - 1, because the indexes always start with 0.
– Rfroes87
That’s right, thank you, I was wrong too another part of the code, but I got vlw
– Thiago Lourenço
https://answall.com/a/451231/112052
– hkotsubo