题目链接
思路:
一开始的思路是想int转字符串再转int,奈何太麻烦,并且stoi()无法通过编译。最后只好乖乖看题解。
从int的末尾开始判断:假设当前数为x,最后反转的数为ans=0.先对x进行一个预处理,防止末尾的0跑到了首位。res = x % 10, ans = ans * 10 + res,x /= 10;最后反转的数int可能存不下,在倒数第二位开始判断是否产生越界。
int转string
int x = pow(2,31)-1;
stringstream s;
string y;
s << x;
y = s.str();
class Solution
{
public:
int reverse(int x)
{
int res = 0;
int ans = 0;
while(x % 10 == 0&&x!=0) x/=10;
while(x != 0) {
res = x % 10;
x /= 10;
if(ans > 214748364|| (ans == 214748364&&res>7)) return 0;
if(ans < -214748364|| (ans == -214748364&&res>8)) return 0;
ans = ans*10 + res;
}
return ans;
}
};