Solution in C++: with string representation


  • 0
    L

    This C++ answer uses string representation and its conversion to/from integer. This is more natural in thinking.

    class Solution {
    public:
        int reverse(int x) {
            bool isNeg = x < 0;
            if (x < 0) { x = -x; }
            
            string strRep = to_string(x);
            string ans;
            for (int i = strRep.size() - 1; i >= 0; i--) {
                ans += string(1, strRep[i]);
            }
            long long int ll = atoll(ans.c_str());
            if (ll > INT_MAX) { return 0; }
            else { return isNeg ? -(int)ll : (int)ll; }
        }
    };
    

    Runtime beats 88% of C++ solutions.


  • 0
    M

    You only compare to INT_MAX, you should also compare to INT_MIN, because abs(INT_MIN) == abs(INT_MAX) + 1, as they are different you would give overflow for abs(INT_MIN) value while INT_MIN is still a good number.


Log in to reply
 

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