题目:
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.
思路:取x绝对值,然后用取余的方法得到翻转的整数。判断正负,判断是否溢出。
Attention: 看到本题,需要考虑到以下几个问题。考察个人思考问题是否全面。
1、负数的情况,怎么处理?
2、原数后面有0,逆转之后怎么处理? 保留还是去掉?
3、逆转之后溢出怎么处理? 32位int的表示范围是–2,147,483,648 ~ 2,147,483,647。 所以很有可能逆转之后就溢出了。对于溢出的问题,需要提前预料到会溢出,然后抛出异常or返回错误状态。或者是再函数的设计上做改变,改变返回值的表达方式。
复杂度:O(1)
Error Code:
class Solution {
public:
int reverse(int x) {
//将整数翻转,保持符号位不变。
//Attention: 最后一个是0,翻转得到什么;需要检查翻转后是否溢出。
//思路:取x绝对值,然后用取余的方法得到翻转的整数。判断正负,判断是否溢出。
int absx = abs(x);
int ret = 0;
//计算翻转后的absx
while(absx)
{
ret = ret * 10 + absx % 10;
absx /= 10;
}
if(ret > INT_MAX)
return 0;
if(x < 0)
ret = -ret;
return ret;
}
};
AC Code:
class Solution {
public:
int reverse(int x) {
//将整数翻转,保持符号位不变。
//Attention: 最后一个是0,翻转得到什么;需要检查翻转后是否溢出。
//思路:取x绝对值,然后用取余的方法得到翻转的整数。判断正负,判断是否溢出。
int ret = 0;
//X取正负数都不影响取余和除10后的符号。可以不分类讨论x。!!!
while(x)
{
//在翻转整数时判断是否有溢出。考虑符号位占一位,所以表示的最大整数时2^31 = INT_MAX/10 !!!
if (abs(ret) > INT_MAX/10)
{ return 0; }
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
};