Simple, Accepted Java Solution - checks overflow and keeps the sign


  • 1
    U
    public int reverse(int x) {
            int reversed = 0;
            
            while (x != 0) {
                int n = reversed * 10 + (x % 10);
                
                if (n / 10 != reversed) { // overflow?
                    return 0;
                }
                x = x / 10;
                reversed = n;
            }
            return reversed;
            
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.