C++ 3 lines


  • 1

    Check overflow both in the loop and at the end:

    int reverse(int x) {
            long ans = 0;
            for (; x != 0 && (INT_MIN <= ans && ans <= INT_MAX); x /= 10) { ans = ans * 10 + x % 10; }
            return (ans < INT_MIN || INT_MAX < ans) ? 0 : ans;
    }
    

    Or only check overflow at the end:

    int reverse(int x) {
            long ans = 0;
            for (; x != 0 ; x /= 10) { ans = ans * 10 + x % 10; }
            return (ans < INT_MIN || INT_MAX < ans) ? 0 : ans;
    }
    

Log in to reply
 

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