C++ solution with string beats 100%


  • 1
    C
    class Solution {
    public:
        int reverse(int x) {
    	string s = std::to_string(x);
    	string result;
    	auto iter = s.end() - 1;
    	for (; iter != s.begin(); iter--) {
    		result += *iter;
    	}
    	result += *iter;
    	try
    	{
    		return std::stoi(x < 0 ? "-" + result : result);
    	}
    	catch (const std::exception&)
    	{
    		return 0;
    	}
        }
    };
    

  • 0
    C

    I think the return value should be long type. Then the try-catch can be deleted.


Log in to reply
 

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