Alternative non-math C++ solution


  • 1
    4

    It's less efficient; I just wanted to show another approach to the problem.

       int reverse( int x )
            {
                stringstream ss;
                string str;
                
                ss << x;
                ss >> str;
                
                int i = 0;
                
                if( str.size() && str[0] == '-' ) ++i;
                
                for( int j = str.size() - 1; j > i; )
                {
                    char temp = str[i];
                    str[i++] = str[j];
                    str[j--] = temp;
                }
                
                ss.clear();
                
                long long out;
                
                ss << str;
                ss >> out;
                
                int out2 = ( int ) out;
                
                if( out != out2 ) return 0;
                return out2;
            }

Log in to reply
 

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