My 12ms C++ solution. Not fast but simple


  • 2
    J

    class Solution {

    public:

    int reverse(int x) {
    stringstream stream;
    long long y = x;
    string s;
    stream << x;
    stream >> s;
    std::reverse(s.begin(), s.end());
    stream.clear();
    stream << s;
    stream >> y;
    if (abs(y) > pow(2, 31) - 1)
    	return 0;
    if (x > 0)
    	return y;
    else
    	return -y;
    

    }
    };


  • 0
    R
    int reverse(int x) {                                                        
        auto str = to_string(x);                                                
        std::reverse(str.begin(), str.end());                                   
        try{                                                                    
            return *(str.rbegin()) == '-' ? -stoi(str) : stoi(str);             
        }                                                                       
        catch(std::out_of_range& err){                                          
            return 0;                                                           
        }                                                                       
    }  
    

    I like STL cause i'm lazy.
    my code is similar as yours


Log in to reply
 

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