class Solution {
public:
int reverse(int x) {
bool flag = 1;
if (x < 0)
{
x = -x;
flag = 0;
}
int res = 0;
while (x!=0)
{
if (abs(res) > INT_MAX/10) return 0; //这个想清楚,学会为什么这么做
res = res * 10 + x % 10;
x /= 10;
}
//if (abs(res) > INT_MAX) return 0;
if (!flag)
return -res;
else
return res;
//int res = 0;
//while (x != 0) {
// if (abs(res) > INT_MAX / 10) return 0;
// res = res * 10 + x % 10;
// x /= 10;
//}
//return res; //网上找的
}
public:
int reverse(int x) {
bool flag = 1;
if (x < 0)
{
x = -x;
flag = 0;
}
int res = 0;
while (x!=0)
{
if (abs(res) > INT_MAX/10) return 0; //这个想清楚,学会为什么这么做
res = res * 10 + x % 10;
x /= 10;
}
//if (abs(res) > INT_MAX) return 0;
if (!flag)
return -res;
else
return res;
//int res = 0;
//while (x != 0) {
// if (abs(res) > INT_MAX / 10) return 0;
// res = res * 10 + x % 10;
// x /= 10;
//}
//return res; //网上找的
}
};
想清楚怎么把数据翻过来,逐步操作即可,不要一次性把所有位置的数都算出来在写(虽然也行),比如一个特别长的数,还是边算边翻过来好点。另外一个要注意的是怎么判断是否超过INT_MAX。