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

22 comments sorted by

View all comments

Show parent comments

1

u/[deleted] Dec 20 '20

I put brackets around that loop, but now only "2" is being printed. I also got rid of the variable "y", because it's unnecessary. I simply replaced "y" with "x" in the second while loop and return statement.

1

u/vigbiorn Dec 20 '20

Part of the issue is 2 is the last digit in the stack, and another is you're only storing the last popped digit.

2 is the last digit because you drop the 3 before pushing it onto the stack.

You're only storing the last digit because you're not adding to x, you're flat-out assigning to it. So 1 gets overwrote by 2 not added to it.

1

u/[deleted] Dec 20 '20

How come the three is getting dropped?

2

u/MarkRems Dec 20 '20

What's the first thing you did in the while (x > 0) loop? Before you even put anything in the stack?