Algorithm

LeetCode #7. Reverse Integer

2017-06-07  本文已影响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;
    }
};

上一篇 下一篇

猜你喜欢

热点阅读