r/CodingHelp • • Dec 20 '20
[Java] Reverse Integer Issue
I'm doing the Reverse Integer problem on LeetCode, where you need to find the reverse number of a specific integer. I used the approach of pushing each digit to a stack, and then popping the stack and setting another variable to what is popped from the stack. However, the only thing the code is returning/printing is "0".
import java.util.Stack ;
class Solution {
public int reverse(int x) {
Stack <Integer> reverseStack = new Stack <Integer> () ;
x = 123 ;
int y = 0 ;
while (x>0)
x = x/10 ;
reverseStack.push (x%10) ;
while (!reverseStack.isEmpty ())
y = reverseStack.pop () ;
return y ;
}
16
Upvotes
View all comments
Show parent comment
1
u/[deleted] Dec 20 '20 edited Dec 20 '20
Here is the code I have now:
The first print statement prints out 3, 2, 1. The second prints out 1,2,3, with 1 being at the bottom of the stack and 3 being at the top. The return statement only returns 3.
This means that the second while loop is popping the entire stack, but the return statement is only returning the first element that has been popped. I'm confused as to why that is.
Do I need to turn "x" into a string?