原题描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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数据存储,然后判断是否溢出的问题
C++代码
class Solution {
public:
int reverse(int x) {
long ret = 0;
while (x != 0) {
ret = ret * 10 + x % 10;
x /= 10;
}
if (ret > INT_MAX || ret < INT_MIN) {
return 0;
}
return (int)ret;
}
};
Bug Free Procedure 从记事本直接写代码
2016.12.01 返回值计算错误
1. $ret = ret * 10 + x \% 10$而不是$ret = ret * (x \% 10)$
2. $ret$初始值应该设置为0,而不是1
3. 不需要单独判断x==0的情况
4. C++中使用INT_MAX和INT_MIN两个宏定义
2016.12.06 逻辑错误
1. while循环的时候的循环条件应该是x!=0
2016.12.13 Bingo!!!一次性AC