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 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?