以下是我AC的代码:
class Solution
{
public:
int reverse(int x)
{
bool flag=false;
if(x<0)
{
x=-x;
flag=true;
}
vector<long long> r;
int i=0;
while(x>0)
{
r.push_back(x%10);
x=x/10;
i++;
}
long long x_=0;
for(int j=0; j<i; j++)
{
int k=i-j-1;
while(k--)
r[j]*=10;
x_+=r[j];
}
if(x_>INT_MAX)
return 0;
if(flag)
x_=-x_;
return x_;
}
};
这是我调试过程中的源代码,添加了不少输出中间变量的语句:
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
class Solution
{
public:
int reverse(int x)
{
bool flag=false;
if(x<0)
{
x=-x;
cout<<x<<endl;
flag=true;
}
vector<long long> r;
int i=0,m=0;
while(x>0)
{
r.push_back(x%10);
cout<<r[m++]<<" ";
x=x/10;
i++;
}
cout<<endl;
long long x_=0;
for(int j=0; j<i; j++)
{
int k=i-j-1;
while(k--)
r[j]*=10;
cout<<r[j]<<endl;
x_+=r[j];
}
if(x_>INT_MAX)
return 0;
if(flag)
x_=-x_;
return x_;
}
};
int main()
{
int x,rx;
cin>>x;
Solution s;
rx=s.reverse(x);
cout<<rx<<endl;
return 0;
}
但个人感觉代码有些冗长,而且在很多地方一不小心就会超了int的范围,比如在 x=-x 那里就非常容易溢出,在 r[j]*=10 的循环那里也很容易超出int的范围(虽说定义的vector是long long型),总感觉AC了也是有些牵强,所以我看了看discuss版,膜拜一下别人写的代码:
甘拜下风。
看来要学习的地方还有很多,特别是这一句ans=ans*10+(x%10); 一下子就解决了我双重循环解决的问题,而且INT_MAX这个也是首次接触,嗯~涨姿势了!