Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
题目看起来很简单,但编写时候发现有些东西需要考虑清楚。
如处理当字符转换后的数是否溢出,以及当输入为-2147483648时,无法将其转换为正整数,因为其对应的正值在signed int类型中属于溢出。
class Solution {
public:
char* changeToChar(const int& x)
{
char *result;
int len=0;
int temp = x;
while(temp != 0)
{
temp = temp/10;
len++;
}
result = new char[len];
temp = x;
int count = 0;
while(temp != 0)
{
result[count] = '0' + temp%10;
temp = temp/10;
count++;
}
result[count] = '\0';
return result;
}
int changeToNum(char* data,const bool& pos)
{
long long num=0;
int len = strlen(data);
int count = 0;
for(;count<len;count++)
{
num = num*10;
num += data[count]-'0';
if((pos&&num > 0x7fffffff)||(!pos&&num>0x80000000))
return 0;
}
return num;
}
int reverse(int x) {
int flag = -1,result=0;
if(x == 0 || x == (signed int)0x80000000)
return 0;
bool pos = true;
if(x<0)
{
pos = false;
x= x*(-1);
}
char* temp = changeToChar(x);
int len;
len = strlen(temp);
if(pos == true)
return changeToNum(temp,pos);
else
return 0-(changeToNum(temp,pos));
}
};
为什么一定要把数字转换为字符串以后再进行逆序呢,这样不仅要消耗存储空间,还增加了运算负担。
优化后的代码如下:
class Solution {
public:
int reverse(int x) {
int ans=0,temp,indicator=1;
if(x < 0)
{
indicator = -1;
x = -x;
}
while(x > 0)
{
temp = ans*10 + x%10;
if(temp/10 != ans)
return 0;
ans = temp;
x = x/10;
}
return ans*indicator;
}
};
如何进行优化才能走到最前面呢。。。