Convert an integer to binary without using the built-in bin function

后端 未结 15 1558
深忆病人
深忆病人 2020-12-07 01:14

This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 01:24

    Just sharing a function that processes an array of ints:

    def to_binary_string(x):
        length = len(bin(max(x))[2:])
    
        for i in x:
            b = bin(i)[2:].zfill(length)
    
            yield [int(n) for n in b]
    

    Test:

    x1 = to_binary_string([1, 2, 3])
    x2 = to_binary_string([1, 2, 3, 4])
    
    print(list(x1)) # [[0, 1], [1, 0], [1, 1]]
    print(list(x2)) # [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0]]
    

提交回复
热议问题