Reverse Integer Solution in Java


  • 0
    V
    public int reverse(int x) {
        if (x == 0) {
            return 0;
        } else if (x > 0 ) {
            return reversePositive(x);
        } else {
            return 0 - reversePositive(Math.abs(x));
        }
    }  
    
    
    public int reversePositive( int x) {
        int result = 0;
        int current = 0;
        int digit;
        while (x > 0)
        {
            current = result;
            digit = x % 10;
            result = result * 10 + digit;
            if(current != (result - digit)/10) {
                return 0;
            }
            x = x/10;
        }
        return result;
    }

Log in to reply
 

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