Reverse a number using stack
Last Updated :
15 Jul, 2022
Given a number , write a program to reverse this number using stack.
Examples:
Input : 365
Output : 563
Input : 6899
Output : 9986
We have already discussed the simple method to reverse a number in this post. In this post we will discuss about how to reverse a number using stack.
The idea to do this is to extract digits of the number and push the digits on to a stack. Once all of the digits of the number are pushed to the stack, we will start popping the contents of stack one by one and form a number.
As stack is a LIFO data structure, digits of the newly formed number will be in reverse order.
Below is the implementation of above idea:
C++
Java
import java.util.Stack;
public class GFG
{
static Stack<Integer> st= new Stack<>();
static void push_digits( int number)
{
while (number != 0 )
{
st.push(number % 10 );
number = number / 10 ;
}
}
static int reverse_number( int number)
{
push_digits(number);
int reverse = 0 ;
int i = 1 ;
while (!st.isEmpty())
{
reverse = reverse + (st.peek() * i);
st.pop();
i = i * 10 ;
}
return reverse;
}
public static void main(String[] args)
{
int number = 39997 ;
System.out.println(reverse_number(number));
}
}
|
Python3
st = [];
def push_digits(number):
while (number ! = 0 ):
st.append(number % 10 );
number = int (number / 10 );
def reverse_number(number):
push_digits(number);
reverse = 0 ;
i = 1 ;
while ( len (st) > 0 ):
reverse = reverse + (st[ len (st) - 1 ] * i);
st.pop();
i = i * 10 ;
return reverse;
number = 39997 ;
print (reverse_number(number));
|
C#
PHP
<?php
$st = array ();
function push_digits( $number )
{
global $st ;
while ( $number != 0)
{
array_push ( $st , $number % 10);
$number = (int)( $number / 10);
}
}
function reverse_number( $number )
{
global $st ;
push_digits( $number );
$reverse = 0;
$i = 1;
while (! empty ( $st ))
{
$reverse = $reverse +
( $st [ count ( $st ) - 1] * $i );
array_pop ( $st );
$i = $i * 10;
}
return $reverse ;
}
$number = 39997;
echo reverse_number( $number );
?>
|
Javascript
<script>
let st = [];
function push_digits(number)
{
while (number != 0)
{
st.push(number % 10);
number = Math.floor(number / 10);
}
}
function reverse_number(number)
{
push_digits(number);
let reverse = 0;
let i = 1;
while (st.length != 0) {
reverse = reverse + (st[st.length - 1] * i);
st.pop();
i = i * 10;
}
return reverse;
}
let number = 39997;
document.write(reverse_number(number));
</script>
|
Time Complexity: O( logN )
Auxiliary Space: O( logN ), Where N is the input number.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...