14 line short C++, no larger integer type used


  • 0
    L
    class Solution {
    public:
        int reverse(int x) {
            int result = 0;
            while (x) {
                if (x > 0 && result > (INT_MAX - x % 10) / 10 
                || x < 0 && result < (INT_MIN - x % 10) / 10) {
                    return 0;
                }
                result = result * 10 + x % 10;
                x /= 10;
            }
            return result;
        }
    };
    

    If x > 0, then we only need to consider positive overflow. If x < 0, we consider negative overflow then.


Log in to reply
 

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