Posted on by Kalkicode
Code Stack

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:

  1. Create an empty custom stack s to store the digits of the number.
  2. Extract the last digit of the number and push it onto the stack s.
  3. Remove the last digit from the number.
  4. Repeat steps 2 and 3 until the number becomes zero.
  5. Pop digits from the stack s one by one and combine them to form the reversed number.

Algorithm

  1. Create a custom stack data structure with push, pop, isEmpty, and peek operations.
  2. Define a function reverse that takes an integer x as input and returns the reversed number.
  3. Create an empty stack s to store the digits of the number.
  4. While x is not equal to zero, do the following: a. Get the last digit of x by taking x % 10. b. Push the last digit onto the stack s. c. Remove the last digit from x by updating x = x / 10.
  5. Initialize a variable multiply to 1.
  6. While the stack s is not empty, do the following: a. Pop the top element from the stack s. b. Multiply the popped element by multiply and add it to x. c. Multiply multiply by 10.
  7. 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

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".

Comment

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