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;
}
};