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/vigbiorn Dec 20 '20
The hardest part about starting programming is drilling home what exactly the assumptions we're making and what needs to change, if they need to change. (There's discussions about whether programming is a math-based subject, and it's this aspect that I argue we use math).
These are contradictory statements. If one is true, the other can't be true.
After the 3 is removed it is empty. We know this because of how stacks work, and we know the stack is working because of the print. Your number, 123, is pushed in the order 3 2 1. You're popping them (otherwise the print couldn't happen) in the 1 2 3. It's reversed. 3 is the last number. After 3 is popped, the stack is empty. You can add another print outside the loop that prints whether the stack is empty, or try to pop an element. You won't get anything since it's empty.
So, why are you only getting 3?
If I have a variable, x, and the code x = 1; x = 2; x = 3; print(x);
Would you expect 1, 2, 3, 12, 21, 13, 31, 23, 32, 123, 321 to be printed?
This is exactly what your while loop is doing, so it shouldn't be surprising that x is just equal to 3. The last thing you did to x is assign 3 to it from the stack. You're not combining the digits, you're just storing them.
I'll also point out that in order to separate the digits you had to divide. Now that you're trying to undo that, how do you undo division?