Home > front end >  Actual answer is 11100 but we got 00111,how to reverse this
Actual answer is 11100 but we got 00111,how to reverse this

Time:04-06

b=[]
def number(num):
    if num==0:
        return
    if num%2==0:
        print("0")
        a=num/2
    else:
        num//2==0
        print("1")
        a=num//2
    return number(a)
number(28)

ans: 0 0 1 1 1

CodePudding user response:

b = []
def number(num):
    if num == 0:
        return b[::-1]
    else:
        if num % 2 == 0:
            b.append("0")
        else:
            b.append("1")
        return number(num // 2)

Result: reversed array of binary answer, that you can join or do something else with.

print(number(28))

Output: ['1', '1', '1', '0', '0']

CodePudding user response:

If you are doing binary to decimal then: try this one line code

print(bin(28)[2:])

if you want a proper function then:

def DecimalToBinary(decimal):       
    if decimal > 1: 
        DecimalToBinary(decimal // 2)
    
    print(decimal % 2, end = '')

a = DecimalToBinary(28)
  • Related