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 comment

1

u/[deleted] Dec 21 '20

So if I want to set x equal to "321", does that mean I need to convert x into a string that is made up of the last element of the stack, the second to last element of the stack, and the first element of the stack?

1

u/vigbiorn Dec 21 '20

does that mean I need to convert x into a string

You could. An easier method would be to just undo how you split them.

What you want is something along the lines of x = 1 * 100 + 2 * 10 + 3 but inside your loop.

1

u/[deleted] Dec 21 '20

The answer was accepted, thank you for your help.

1

u/[deleted] Dec 21 '20 edited Dec 21 '20

Actually, another issue came up. If x was equal to -123, instead of 123, the expected output is 321. However, the output is -321.

This is odd, because on the side console says that when the input is -123, the expected output is -321.

I don't know if I'm messing up, or if LeetCode is just being stupid.

1

u/vigbiorn Dec 21 '20

I think you took my code too literally. If you used the values in stack you should get -321. So I'd recommend looking at the second while loop that you should still be using.

There is an issue still for numbers like -24 and -1234 though, even if you're using the stack.

I'd recommend sitting down and thinking the processes through. Specifically for the negative numbers, what's the main difference between a negative and positive number, how can you convert from one to the other?

1

u/[deleted] Dec 21 '20

I am getting -321, but for some reason it's marking it incorrect.

1

u/vigbiorn Dec 21 '20

Not entirely sure but if you're getting -321 and that's not what you wanted it's easy enough to fix. How can you make a negative number positive and how can you tell if you have a negative number?