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:
- First, the remainder of the
num
divided by 10 is stored in the variabledigit
. Now, thedigit
contains the last digit ofnum
, 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
contains0 * 10 + 4 = 4
.num
is then divided by 10 so that now it only contains the first three digits: 123. - After second iteration,
digit
equals 3, reversed equals4 * 10 + 3 = 43
andnum = 12
. - After third iteration,
digit
equals 2, reversed equals43 * 10 + 2 = 432
andnum = 1
. - After fourth iteration,
digit
equals 1, reversed equals432 * 10 + 1 = 4321
andnum = 0
. - Now
num = 0
, so the test expressionnum != 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.
Learn how to reverse a number in python.
Reversing a number means rearranging the digits in a number such that the last digit comes first, followed by the second last digit and so on, and the first digit is at the end. There are numerous ways to reverse a number in python, which are discussed below. We are
given a number that has to be reversed. That means we need the last digit to come first, followed by the second last digit and so on, and the first digit will come last. One way of achieving this is by using the while loop. The condition for the while loop will be till our original number has non-zero digits left, i.e., till the original number is not equal to zero. We will initialize a new variable that will store our reversed number, so we need to add the last digit
first in this number. In the while loop, we can take the modulo of the number with ten to get the last digit. The answer to this will be the last digit. Now we need to add this digit to our reversed number, but it is possible that the reversed number already contains some digits. If we simply add this digit, it will result in the wrong answer. So we first need to shift all existing digits in the reversed number by one place. Hence, we multiply the reversed number with 10 and
add this digit. The current last digit of the original number has been added to the reversed number and hence should be removed. So, we divide the original number by 10 and take its floor, so the last digit is removed. The process continues until our original number becomes 0, and we get the reversed number in our variable. Code:Overview
Scope
Reversing a number using a while loop
# the number to be reversed num = 529412 # the number after reversal reversed_num = 0 # start a while loop till complete number has been reversed while num != 0 : # taking modulo with 10 gives us the last digit of num curr_digit = num % 10 # appending the last digit of num to reversed_num # for this we multiply the curr reversed_num by 10 and add curr_digit to it reversed_num = 10*reversed_num reversed_num = reversed_num + curr_digit # remove the last digit from num by dividing it by 10 num = num // 10 # we get the reversed_num print["Reversed Number is: " + str[reversed_num]]
Output:
Reversed Number is: 214925
Reversing a number using String-Slicing
To reverse a number by this method, we use the property of strings, which is string slicing. Slicing is obtaining the substring of a string in python.
The exciting thing about slicing is that if we use -1 as a parameter, we can obtain the substring from the end, thus reversing the number. Hence, in this method, we first convert our number to a string, and then by slicing, we reverse it.
Code:
# the number to be reversed num = 97402 #convert number to string num_string = str[num] # store the size of the number size = len[num_string] # use slicing to reverse reversed_num = num_string[size::-1] #output reversed number print["Reversed Number is: " + reversed_num]
Output:
Reversed Number is: 20479
Reversing a number using Recursion
To reverse a number by this method, we use recursion. The thing with recursion is that we can keep calling the recursive function again and again till we reach the last index.
This will be our base case, where we can then start adding the characters to the resultant reversed string. So, the characters will be added this way: the last index followed by the second last index and so on, and the first index will be added at the end.
In this way, we can reverse the string by calling the recursive function first and adding the character later.
Code:
def reverse[n] : #if no digits remain if len[n]==0 : return n #else add the first digit to the end and recurse for remaining number return reverse[n[1:]] + n[0] # the number to be reversed num = 1749 #convert number to string num_string = str[num] #call the recursive function to reverse num reversed_num = reverse[num_string] #output reversed number print["Reversed Number is: " + reversed_num]
Output:
Reversing a number using for loop
To reverse a number by this method, we keep adding the characters from the back of the original string to a new string using a for a loop. In this way, the new string so formed is reversed, as the last character is added first to it, followed by the second last, and so on and the first character is added last.
Code:
# the number to be reversed num = 38954 #convert number to string num_string = str[num] # initialize a variable that will store the reversed number reverse_num = '' #start a for loop to reverse the number for i in range[0,len[num_string]]: #add the current digit to the start of the reversed number reverse_num = num_string[i] + reverse_num #we get the reversed number in reverse_num print["Reversed Number is: " + reverse_num]
Output:
Reversed Number is: 45983
Reversing a number using reversed Method
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.
Code:
# the number to be reversed num = 982447 #convert number to string num_string = str[num] #reverse the string using reversed method reversed_num = "".join[reversed[num_string]] #output reversed number print["Reversed Number is: " + reversed_num]
Output:
Reversed Number is: 744289
Reversing a number using the List
In this method, we utilize the fact that python provides a reverse[] method for lists by which the elements of a list get reversed.
So, we just add the digits of our number into a list using the list[] function in python, then use the reverse method on it to get the digits in reverse order and then by using the join[] method, we obtain the final reversed number.
The join[] method in python is used to convert an iterator into one single string. To obtain the reversed string from this iterator, we use the join[] method of python and store the output in reversed_num.
Code:
# the number to be reversed num = 629378 #convert number to string num_string = str[num] #convert the number into a list number_list = list[num_string] #use the reverse method of the list to reverse the list number_list.reverse[] #convert the list into number again reversed_num = ''.join[number_list] #output reversed number print["Reversed Number is: " + reversed_num]
Output:
Reversed Number is: 873926
Reversing a number using the Stack
This method utilizes the property of the stack. A stack stores elements in the LIFO or Last In First Out order. This means that the elements that are pushed at the end of the stack are the ones that are removed first.
So, intuitively if we push all the digits of our number from the start into the stack, when popping them out, they will be in the reverse order, and we can store them to get the final reversed number.
Code:
# Function to create a stack def create_stack[]: st = [] return st # Function to push an element into the stack def push[st,ele]: st.append[ele] # Function to pop an element from the stack def pop[st]: # If the size of the stack is 0 if len[st] == 0: return return st.pop[] # Function to reverse a number using stack def reverse[num]: # Finding the length of the number n = len[num] # Creating a stack st = create_stack[] # Inserting digits in stack for i in range[0,n]: push[st,number[i]] reversed_num = "" # Poping the digits from the stack to get the reversed number for i in range[0,n]: reversed_num = reversed_num + pop[st] return reversed_num number = "123456" print["Reversed Number is: " + reverse[number]]
Output:
Reversed Number is: 654321
Conclusion
- In this article, we learned how to reverse a given number in python. The article explored the various methods and their respective implementations that can be employed to reverse a number in python. Some involve changing the number into a string and using some string methods, while others involve while loop, for loop, recursion, or stacks.