Problem:Reverse Integer
Question
- Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
思路
将整数倒置,直接调用C++的to_string()函数(用绝对值),然后利用stoi函数再转化为int类型,stoi会在溢出的时候throw一个异常,非常方便
解题代码
class Solution {
public:
int reverse(int x) {
int sign = x < 0? -1 : 1;
x = (x < 0 ? abs(x) : x);
string str = to_string(x);
std::reverse(str.begin(), str.end());
int result = 0;
try {
result = stoi(str);
} catch(...){
return 0;
}
return result*sign;
}
};