Binary numbers from N digits

to generate binary numbers in ndigit
I did this to get up to 16 binary numbers.

n = 6                       # for 6 digits
for i in xrange(16):
    b = bin(i)[2:]
    l = len(b)
    b = str(0) * (n - l) + b
    print b

it looks like this

000000
000001
000010
000011
000100
000101
000110
000111
001000
001001
001010
001011
001100
001101
001110
001111

but I want to get these values ​​without adding a series to the prefix 0s.
can anyone help me on this. thank

+4
source share
3 answers

Delete the line that 0s is on.

n = 6
for i in xrange(16):
    b = bin(i)[2:]
    l = len(b)
    #b = str(0) * (n - l) + b  # <--------
    print b

If you mean mileage without a string oeprator, use str.formatwith the bformat :

n = 6
for i in xrange(16):
    print '{:0{}b}'.format(i, n)
    # OR  print '{:06b}'.format(i)

    # OR  print '{:b}'.format(i)  if you want no leading 0s.
+7
source

If you request another method:

n = 6
for i in xrange(16):
    b = bin(i)[2:].zfill(n)
    print b

str.zfill(n) , n.


:

for i in xrange(16):
    b = bin(i)[2:]
    print b
+5

With this code, you can generate a list of binary numbers up to n in O (2 ^ int (log (n))) time complexity.


import math

num=25

n=int(math.log(num,2))

x=['0','1']

for i in range(1,int(n)+1):

        for j in range(0,2**i):  

        x.append('1'+x[j])

        x[j]='0'+x[j]



print(x[0:num])

output ::

['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', '11000']

hope this helps

-1
source

All Articles