【题】
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
【题目分析】
这道题主要是对于溢出情况的处理。用long long类型的变量存放转换后的值。
【具体代码如下】
int reverse(int x) {
if(x==0)return 0;
int sign=1;
int pox_x;
if(x>0)pox_x=x;
else
{
sign=-1;
pox_x=-x;
}
int rev_x;
if(x%10==0)return reverse(x/10);
int number[10];
int i=0;
int digits=0;
while(pox_x>0)
{
number[i]=pox_x%10;
pox_x=pox_x/10;
i++;
}
int j=0;
long long count=0;
while(j<i)
{
count=count*10+number[j];
j++;
}
if(count>2147483647)return 0;
else rev_x=count;
return rev_x*sign;
}
【个人总结】
其实这道题我的解法是过于麻烦了。首先,对于x=1000这类情况,可以不用另外分情况讨论,递归的求解导致时间花费多。其次,当确定用 long long 类型后,不用新建一个number[10]数组,因为int型最大就是10位数,而long long 范围是 -9223372036854775808 ~ +9223372036854775807 ,它占用8个字节。所以这点上处理不恰当,啰嗦冗余。