题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
我是这样写的:
class Solution {
public:
int reverse(int x) {
// int temp = INT_MAX;
int count = ;
int y = x;
while(abs(y) > )
{
y = y/;
count++;
}
if(x == )
return ;
else if(x > )
{
int *a = new int[count];
for(int i = ; i < count; i++)
{
a[i] = x%;
x = x/;
}
int value = ;
int temp = ;
for(int j = ; j < count; j++)
{
value = value* + a[j];
if(temp != (value - a[j])/) value = temp = ;
else temp = value;
}
delete []a;
return value;
}
else
{
x = -x;
int *a = new int[count];
for(int i = ; i < count; i++)
{
a[i] = x%;
x = x/;
}
int value = ;
int temp = ;
for(int j = ; j < count; j++)
{
value = value* + a[j];
if(temp != (value - a[j])/) value = temp = ;
else temp = value;
}
delete []a;
return -value; } }
};
通过之后,我参考了网友doc_sgl的代码
http://blog.csdn.net/doc_sgl/article/details/12190507
他是这样写的:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function long res = ;
while(x)
{
res = res* + x%;
x /= ;
}
return res;
}
十几行与几十行的区别,却能更简便的表述。虽然这些代码没有仔细思量裁剪,但却表现了代码能力的区别。以此自省之。