美文网首页Algorithm
LeetCode #7. Reverse Integer

LeetCode #7. Reverse Integer

作者: 匠_心 | 来源:发表于2017-06-07 17:32 被阅读0次

    Reverse digits of an integer.

    Example1:

        x = 123, return 321
    

    Example2:

        x = -123, return -321
    

    Solution:

    class Solution
    {
      public:
        int reverse(int x)
        {
            stringstream ss{};
    
            string s1{};
            ss << x;
            char ch;
            ss.get(ch);
            if (ch != '-')
                ss.unget();
            else
                s1.push_back('-');
    
            string s{};
            ss >> s;
            for (auto iter = s.crbegin(); iter != s.crend(); ++iter)
            {
                s1.push_back(*iter);
            }
    
            stringstream ss1{s1};
            int result;
            ss1 >> result;
            // return 0 when the reversed integer overflows.
            if (result == 2147483647 || result == -2147483648)
                return 0;
            return result;
        }
    };
    
    

    相关文章

      网友评论

        本文标题:LeetCode #7. Reverse Integer

        本文链接:https://www.haomeiwen.com/subject/redafxtx.html