Reverse a number using stack
The problem is to reverse a given number using a stack. The goal is to reverse the digits of the number, maintaining the sign if it is a negative number, and ignoring leading zeroes if present in the original number.
Idea to Solve the Problem
To reverse the number using a stack, we will follow these steps:
- Create an empty custom stack
s
to store the digits of the number. - Extract the last digit of the number and push it onto the stack
s
. - Remove the last digit from the number.
- Repeat steps 2 and 3 until the number becomes zero.
- Pop digits from the stack
s
one by one and combine them to form the reversed number.
Algorithm
- Create a custom stack data structure with push, pop, isEmpty, and peek operations.
- Define a function
reverse
that takes an integerx
as input and returns the reversed number. - Create an empty stack
s
to store the digits of the number. - While
x
is not equal to zero, do the following: a. Get the last digit ofx
by takingx % 10
. b. Push the last digit onto the stacks
. c. Remove the last digit fromx
by updatingx = x / 10
. - Initialize a variable
multiply
to 1. - While the stack
s
is not empty, do the following: a. Pop the top element from the stacks
. b. Multiply the popped element bymultiply
and add it tox
. c. Multiplymultiply
by 10. - Return the reversed number
x
.
Pseudocode
FUNCTION reverse(x):
num = x
s = new MyStack()
WHILE num is not 0:
s.push(num % 10)
num = num / 10
multiply = 1
WHILE s is not empty:
num = s.pop() * multiply + num
multiply = multiply * 10
RETURN num
Code Solution
-
1) Reverse a number using stack in java
2) Reverse a number using stack in c++
3) Reverse a number using stack in c
4) Reverse a number using stack in golang
5) Reverse a number using stack in c#
6) Reverse a number using stack in vb.net
7) Reverse a number using stack in node js
8) Reverse a number using stack in typescript
9) Reverse a number using stack in python
10) Reverse a number using stack in ruby
11) Reverse a number using stack in scala
12) Reverse a number using stack in swift
13) Reverse a number using stack in kotlin
14) Reverse a number using stack in php
Time Complexity Analysis
Let n be the number of digits in the input number. The time complexity of the reverse
function is
O(n) because we need to iterate through each digit of the number and perform stack operations.
Output Explanation
The output shows the number before and after reversing using the reverse
function. For example,
"Before -381725 After -527183" represents the original number -381725, and the reversed number is -527183.
Similarly, for other test cases, the numbers are reversed accordingly. Note that leading zeroes are ignored in
the reversed number, as shown in the output "Before 12340 After 4321".
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment