A solution in C with comments.


  • 0
    Q
    int reverse(int x) {
        // First check whether x is negative;
        // we can reverse it first and make it negative
        // again later.
        int signum = x < 0 ? -1 : 1;
        x *= signum;
        
        // One at a time, take the units digit from x and
        // put it on to reversed, then shift x right one digit.
        int reversed = 0;
        while (x) {
            reversed *= 10;
            reversed += x % 10;
            x /= 10;
        }
        
        // Re-apply the negative sign if there was one.
        return reversed * signum;
    }
    

  • 0
    H

    So, how about the overflow problem?


Log in to reply
 

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