Hướng dẫn reverse integer python

Example 1: Reverse a Number using a while loop

num = 1234
reversed_num = 0

while num != 0:
    digit = num % 10
    reversed_num = reversed_num * 10 + digit
    num //= 10

print("Reversed Number: " + str(reversed_num))

Output

4321

In this program, while loop is used to reverse a number as given in the following steps:

  1. First, the remainder of the num divided by 10 is stored in the variable digit. Now, the digit contains the last digit of num, i.e. 4.
    digit is then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in the reversed number. One-th place multiplied by 10 gives you tenth place, tenth gives you hundredth, and so on. In this case, reversed_num contains 0 * 10 + 4 = 4.
    num is then divided by 10 so that now it only contains the first three digits: 123.
  2. After second iteration, digit equals 3, reversed equals 4 * 10 + 3 = 43 and num = 12.
  3. After third iteration, digit equals 2, reversed equals 43 * 10 + 2 = 432 and num = 1.
  4. After fourth iteration, digit equals 1, reversed equals 432 * 10 + 1 = 4321 and num = 0.
  5. Now num = 0, so the test expression num != 0 fails and while loop exits. reversed already contains the reversed number 4321.

Example 2: Using String slicing

num = 123456
print(str(num)[::-1])

Output

654321

Using the string slicing concept, you can get reverse the string. ::-1 corresponds to start:stop:step. When you pass -1 as step, the start point goes to the end and stop at the front.

Nội dung chính

  • Introduction to Reverse Number in Python
  • Logic for Reverse Number in Python
  • Reversing the Number Using different ways in Python
  • Recommended Articles
  • Can you reverse a number in Python?
  • How do you reverse a single number in Python?
  • How do you reverse a number without a loop?
  • How do you reverse a number in a list Python?

Introduction to Reverse Number in Python

Reverse operation in python can be defined as a process of turning the order of the input assigned to a variable from back to front or front to back. This operation can be achieved by any kind of logic involving the conditional statements of python, such as for loop, while conditional statement, if condition, etc. There are multiple pre-defined methods in python which can be worked along with the conditional statements for creating reverse logical function, and they are list method, slice method, recursion method, etc. Reverse() method is the straightforward method for performing this operation for any kind of input provided by the user.

Logic for Reverse Number in Python

The below points briefly us about how to reverse a given number in python:

  • The input number can be read by using input () or raw_input () method.
  • Next, check whether the entered value is an integer or not.
  • Now check whether a given integer is greater than 0 or not.
  • Create a variable called reverse and initialize the variable value with 0.
  • Now find the remainder for the given input number by using the mod (%) operator.
  • Multiply the variable reverse with 10 and add the remainder value to it.
  • Now floor (floor division is performing the division operation and resulting value provides lower integer to the value) divide the given input number with 10.
  • The given input number will become 0 at some point.
  • Now repeat the steps 5, 6, 7 until you get the input number is not greater than zero.
  • In the last step, display the variable in reverse.

Reversing the Number Using different ways in Python

Below are the different ways in Python:

1. Using Slicing Method

Code:

def reverse_slicing(s):
    return s[::-1]
my_number = '123456'
if __name__ == "__main__":
    print('Reversing the given number using slicing =', reverse_slicing(my_number))

Execution Steps:

  • Save the python code in your drive. (Here, we have used D drive for executing the programs)
  • Now open the command prompt and locate your drive.
  • Execute the program with the command as python program_name.py
  • The python programs will be saved with .py extension.

Output:

Note: Follow the above steps for executing the python programs for reversing which are going to be discussed below.

2. Using For loop Method

Code:

def reverse_for_loop(s):
s1 = ''
for c in s:
s1 = c + s1
return s1
my_number = '123456'
if __name__ == "__main__":
print('Reversing the given number using for loop =', reverse_for_loop(my_number))

Output:

3. While Loop Method

Code:

def reverse_while_loop(s):
    s1 = ''
    length = len(s) - 1
    while length >= 0:
        s1 = s1 + s[length]
        length = length - 1
    return s1
my_number = '123456'
if __name__ == "__main__":
    print('Reversing the given number using while loop =', reverse_while_loop(my_number))

Output:

4. Using Reversed Method

Code:

def reverse(string): 
	string = "".join(reversed(string)) 
	return string 
my_number = "123456"
print ("The given number is : ",end="") 
print (my_number) 
print ("Reversing the given number using reversed is : ",end="") 
print (reverse(my_number)) 

Output:

5. Using user-entered number and then reversing it

Code:

My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
while(My_Number > 0):
 Reminder = My_Number %10
 Reverse_Number = (Reverse_Number *10) + Reminder
 My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)

Output:

6. Two-Digit Reverse Method

Code:

My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
temp = Reverse_Number
Reminder = 1
for i in range (Reminder+1):
 Reminder = My_Number %10
 Reverse_Number = (Reverse_Number *10) + Reminder
 My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)

Output:

7. Three-Digit Reverse Method

Code:

My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
temp = Reverse_Number
Reminder = 1
for i in range (Reminder+2):
 Reminder = My_Number %10
 Reverse_Number = (Reverse_Number *10) + Reminder
 My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)

Output:

8. Without the Recursion Method

Code:

my_num=str(input("Enter the number to be reversed: "))
print("Reverse of the given number is: ")
print(my_num[::-1])

Output:

9. With Recursion Method

Code:

def reverse(s): 
	if len(s) == 0: 
		return s 
	else: 
		return reverse(s[1:]) + s[0] 
my_number = "123456789"
print ("The given number is : ",end="") 
print (my_number) 
print ("Reversing the given number using recursion is : ",end="") 
print (reverse(my_number))

Output:

10. Using Function Method

Code:

def rev_number(My_Number) :    
    reverse_num = 0
    while(My_Number) :
        Reminder = My_Number % 10
        reverse_num = reverse_num* 10 + Reminder
        My_Number //= 10
    return reverse_num
if __name__ == "__main__" :
    My_Number = int(input('Please provide the number to be reversed:: '))
    print('Reverse of the provided number is: ', rev_number(My_Number))

Output:

11. Using List Method

Code:

number = "123456789"
print ("The given number is : " + number)
#converting number into list
list1 = list(number)
#applying reverse method of list
list1.reverse()
#converting list into number
number = ''.join(list1)
print ("Reverse of the provided number is : " + number)

Output:

12. Using the Stack Method

Code:

def create_stack():
  #creating a list as stack and return it
  stack = []
  return stack
def push(stack,element):
  #adding new element to list
  stack.append(element)
def pop(stack):
  #deleting the last element from the list
  if len(stack) == 0:
    return
  return stack.pop()
def reverse(number):
  #reversing the number by using stack's functions
  num = len(number)  
  #creating empty list (stack)
  stack = create_stack()
  #inserting number into list
  for i in range(0,num):
    push(stack,number[i])
  number = ""
  #getting last element of the stack list
  for i in range(0,num):
    number = number + pop(stack)
  return number
number1 = "123456789"
number2 = reverse(number1)
print ("The given number is : " + number1)
print ("Reverse of the given number is : " + number2)

Output:

Conclusion

So far in this tutorial, we have learned to find the reverse number of a given number in python. This program runs only once, i.e. it asks the user to enter a number, find the reverse value, print and exit. We can also insert it into an infinite loop for continuous reading of a new number from the user. Put it in an infinite loop and check what’s going on.

This is a guide to Reverse Numbers in Python. Here we discuss the logic for Reverse Number in Python and top 12 methods of Reverse Number in Python. You can also go through our other related articles to learn more –

  1. Random Number Generator in Python
  2. Math Functions in Python
  3. Python Sets
  4. Python Features

Can you reverse a number in Python?

We use the python reversed() function to reverse a number by this method. This function returns a pointer that can iterate the string/list in reverse order. We use the join() method of python to obtain the reversed number from this iterator finally.

How do you reverse a single number in Python?

Reverse Number In Python.

# Python Program to Reverse a Number using While loop..

Number = int(input("Please Enter any Number: ")).

Reverse = 0..

while(Number > 0):.

Reminder = Number %10..

Reverse = (Reverse *10) + Reminder..

Number = Number //10..

print("\n Reverse of entered number is = %d" %Reverse).

How do you reverse a number without a loop?

How to reverse a 3 digit number.

Declare the int into num1, num2 and num3 along witht the output, reverse..

Ask the user to enter a number to reverse..

Store the number using scanf..

Get the last digit of the number , num1= n/100..

Get the middle digit from the user, num2=(num%100)/10..

How do you reverse a number in a list Python?

In Python, there is a built-in function called reverse() that is used to revers the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which have to be reversed.