Home > Software design >  How can I reverse a number?
How can I reverse a number?

Time:12-15

This is my code:

Main_Input = int(input())

print("_________________")
while Main_Input > 0:
    c1 = Main_Input % 2
    Main_Input = Main_Input // 2
    print(c1)

I want to convert all the output value of "c1" variable into a whole number and reverse it. How can I do this?(This code is for converting natural numbers to binary numbers)

I searched the internet but could not find anything. I am a beginner programmer.

CodePudding user response:

As you mentioned This code is for converting natural numbers to binary numbers

The easiest way would be

Main_Input = int(input())

bin(Main_Input)[2:]

If you want to reverse it:

bin(Main_Input)[2:][::-1]

with while loop:

Main_Input = int(input())
remainder = 0
x = ""
n = Main_Input 

while n > 0:  
    remainder = (n%2)
    x = str(remainder)   x
    n = n//2

print(x, "is the binary of", Main_Input)

CodePudding user response:

MainInput=int(input())print("_________________")while Main_Input > 0rev = Main_Input % 2 Main_Input=Main_Input // 2print(rev)

  • Related