LeetCode之6:Reverse Integer
问题描述:
返回一个整形数字的倒序下的数字。题目地址
问题的陷阱与难点:
- 思路很好想,但是可能会漏掉几个越界判断。
缺陷代码(62.81%)
public int reverse(int x) {
int negative;
negative = x < 0 ? -1 : 1; //记录数字的正负
Long min = (long)(Integer.MAX_VALUE * -1); //记录转换成绝对值后可以接受的最小负数
if (min > x) { //注意,这里这样写是错误的!!!请用long存储原数的绝对值。
return 0;
}
Stack<Long> stack = new Stack<Long>();s s
x = x * negative;
while (x != 0) {
stack.push((long)(x % 10));
x = x / 10;
}
Long value = 0L;
int i = 1;
while (!stack.isEmpty()) {
value = value + i * stack.pop();
i *= 10;
}
if (value > Integer.MAX_VALUE) { //如果越界,返回0
return 0;
} else {
return (int)(value * negative);
}
}
思路
这道题主要考察的是鲁棒性。 思路是借助 求余 操作 获取 每一位,并存储到栈或者队列中,然后再取出来乘相应位的系数求和。下面只强调一下鲁棒性所需要注意的点。
- 如果原数是负数,而且它的绝对值大于 整形最大值时, 就不能单纯的用一个 整形 存放它的绝对值,而要用long。