我已开始的策略其实是直接转字符串操作一下完了:
int reverse(int x) {
if (x == 0){
return 0;
}
while (x % 10 == 0){
x /= 10;
}
auto&& s = to_string(x);
auto result = atoll(string(s.crbegin(), s.crend()).data());
if (result > INT32_MAX){
return 0;
}
return static_cast<int>(x < 0? -result : result);
}
但是这效率低啊,于是联想到上一个判断回文数的问题,我就改成了:
int reverse(int x) {
long long result = 0;
while (x != 0){
result = result * 10 + x % 10;
x /= 10;
}
if (result > INT32_MAX || result < INT32_MIN){
return 0;
}
return static_cast<int>(result);
}