Showing posts with label Do you know. Show all posts
Showing posts with label Do you know. Show all posts

Do you know, How to reverse a number using stack?

 
Given a number, write a program to reverse this number using stack operations like push(), and pop() in Java. For example

Do you know, How to reverse a number using stack?

Input: 123456
Output: 654321
Input: 900
Output: 9
Lets see simple java program to reverse a number using stack operation 

import java.util.Stack;

public class ReverseNumber {

 public static void main(String[] args) {
  
  int number = 123456;
  
  System.out.println(reverseNum(number));
 }
 
 public static int reverseNum(int number) {
  Stack<Integer> stack = new Stack<Integer>();
  int counter = 1;
  while(number >0) {
   stack.push(number%10);
   number = number/10;
  }
  number = 0;
  while(stack.size() > 0) {
   number = number + (stack.pop() * counter);
   counter *= 10;
  }
  return number;
 }
}
OUTPUT:

654321