-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse.java
49 lines (43 loc) · 1.16 KB
/
reverse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Java program to reverse the num using a stack
import java.util.Stack;
import java.util.*;
public class StackProgram
{
// Stack to maintain order of digits
static Stack<Integer> st= new Stack<>();
// Function to push digits into stack
static void push_digits(int num)
{
while(num != 0)
{
st.push(num % 10);
num = num / 10;
}
}
// Function to reverse the num
static int reverse_num(int num)
{
// Function call to push num's
// digits to stack
push_digits(num);
int reverse = 0;
int i = 1;
// Popping the digits and forming
// the reversed num
while (!st.isEmpty())
{
reverse = reverse + (st.peek() * i);
st.pop();
i = i * 10;
}
// Return the reversed num formed
return reverse;
}
// Driver program to test above function
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println(reverse_num(num));
}
}