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

后端 未结 15 1557
深忆病人
深忆病人 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:32

    Not really the most efficient but at least it provides a simple conceptual way of understanding it...

    1) Floor divide all the numbers by two repeatedly until you reach 1

    2) 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.

    Here's the literal implementation of that:

    def intToBin(n):
        nums = [n]
        while n > 1:
            n = n // 2
            nums.append(n)
    
        bits = []
        for i in nums:
            bits.append(str(0 if i%2 == 0 else 1))
        bits.reverse()
        print ''.join(bits)
    

    Here's a version that better utilizes memory:

    def intToBin(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)
    

提交回复
热议问题